Initialize state with async data in Redux - reactjs

I want to populate two tokens properties via AJAX whenever the state is created. It seems that Redux doesn't have much documentation on this. I can't use componentWillMount to do this because the way I have my containers set up it just won't work.
const Auth = Record({
token: '',
yelpToken: '',
});
Is there someway run a function that will happen before createStore is invoked?

You can replace your index with this:
class EntryPoint extends Components {
constructor(){
this.state = {
//can be replaced with store state..
finishedFetching: false
}
}
componentDidMount() {
//you can chain dispatches with redux thunk
dispatch(fetchAsyncData())
.then(() => this.setState({finishedFetching: true}))
}
render() {
return this.state.finishedFetching ? <App/> : null;
}
}

Related

React redux current user param gets too late to use

The problem lays in the code below
class GroupsPage extends React.Component {
constructor(props){
super(props);
this.state = {
groups: [],
}
}
async fetchGroups (){
fetchGroupsFirebase().then((res) => {this.setState({groups:res})})
};
async componentDidMount() {
await this.fetchGroups();
}
render(){}
const mapStateToProps = createStructuredSelector({
user: selectCurrentUser
})
export default connect(mapStateToProps)(GroupsPage);
As you see , i call fetchGroups to get some data from firebase, it works allright but i want to get specific data for my current user, my problem is that i can't send de currentUser id as a param to the fetchGroupsFirebase functions, because at the time of the call, this.props.user is still null , and it gets the value from mapStateToProps only after the component mounted.
I hope that i am clear enough, i know it is messy
TLDR: I need the user id but when i get it it's too late
what you would need to do is to first check if the user prop is available right after the mount - if not skip the api call and wait untill the user prop gets updated using componentDidUpdate lifecycle method.
This way, your api call will be made as soon as the user prop gets injected to the component.
class GroupsPage extends React.Component {
constructor(props) {
super(props);
this.state = {
groups: [],
};
}
async fetchGroups(id) {
fetchGroupsFirebase(id).then((res) => {
this.setState({ groups: res });
});
}
async componentDidMount() {
if (this.props.user) {
await this.fetchGroups(this.props.user);
}
}
async componentDidUpdate(prevProps) {
if (this.props.user && this.props.user !== prevProps.user) {
await this.fetchGroups(this.props.user);
}
}
render() {}
}
const mapStateToProps = createStructuredSelector({
user: selectCurrentUser,
});
export default connect(mapStateToProps)(GroupsPage);

How middleware in react life cycle works?

I am new in react js. I have started doing a small product with react-redux. I am using saga middle-ware.
What i have done is as under.
This is the component
//all import work
import { activateAuthLayout, onLoad } from '../../../store/actions';
class EcommerceProductEdit extends Component {
constructor(props) {
super(props);
this.state = {
checked: false,
unselected_lists: [],
main_checked: false
}
//here I get the products props always null
console.log(this.props);
}
componentDidMount() {
this.props.activateAuthLayout();
//dispatching an action to fetch data from api, done in midddleware
if (this.props.user !== null && this.props.user.shop_id)
this.props.onLoad({
payload: this.props.user
});
}
render() {
//here I get the products props
console.log(this.props);
return (
//jsx work
);
}
}
const mapStatetoProps = state => {
const { user, is_logged_in } = state.Common;
const { products, is_loading } = state.Products;
return { user, is_logged_in, products, is_loading };
}
export default withRouter(connect(mapStatetoProps, { activateAuthLayout, onLoad })(EcommerceProductEdit));
Action is
import { FETCH_PRODUCT, FETCH_PRODUCT_SUCCESS } from './actionTypes';
export const onLoad = (action) => {
return {
type: FETCH_PRODUCT,
payload: action.payload
}
}
export const productFetched = (action) => {
return {
type: FETCH_PRODUCT_SUCCESS,
payload: action.payload
}
}
Reducer is
import { FETCH_PRODUCT_SUCCESS } from './actionTypes';
const initialState = {
products: null,
is_loading: true
}
export default (state = initialState, action) => {
switch (action.type) {
case FETCH_PRODUCT_SUCCESS:
state = {
...state,
products: action.payload,
is_loading: false
}
break;
default:
state = { ...state };
break;
}
return state;
}
And saga is
import { takeEvery, put, call } from 'redux-saga/effects';
import { FETCH_PRODUCT } from './actionTypes';
import { productFetched } from './actions';
import agent from '../../agent';
function* fetchProduct(action) {
try {
let response = yield call(agent.Products.get, action.payload);
yield put(productFetched({ payload: response }));
} catch (error) {
if (error.message) {
console.log(error);
} else if (error.response.text === 'Unauthorized') {
console.log(error)
}
}
}
function* productSaga() {
yield takeEvery(FETCH_PRODUCT, fetchProduct)
}
export default productSaga;
I am being able to get the products props only in render function. How would i be able to get it it in constructor ?
I would be really grateful if anyone explained me about react life cycle a little bit more.
Thanks.
updated
a constructor is called during object instantiation. According to the docs "The constructor for a React component is called before it is mounted". So if the props passed to the component are being changed after the component has been mounted you can use componentWillReceiveProps life cycle methods.
componentWillReceiveProps is deprecated so you can use componentDidUpdate instead. Example from the docs.
componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.userID !== prevProps.userID) {
// update your component state from here.
this.fetchData(this.props.userID);
}
}
MiddleWare: Middleware just comes in between the flow after the action has been dispatched and before it reaches the reducers, like in your case once you fire onLoad action and before it reaches the reducers, its caught in Saga middleware which executes it according to code written in it
Lifecycle in your case goes the following way:
In your compoenentDidMount method, you dispatch an action of onLoad. The action type in such a case becomes "FETCH_PRODUCT" and same action is now caught in Saga.
Since this is async call, the code in your component continues executing while the Saga perform its action in parallel. It calls API through this line of code: yield call(agent.Products.get, action.payload); . Once API call is completed, it dispatches an action 'productfetched' through this line of code yield put(productFetched({ payload: response }));.
Now this action reaches reducer and modify the state of "products". Since the product state in your redux is modified, your component EcommerceProductEdit re-renders and you get your product list in render method. The point to be noted is that the flow must have already finished executing inside componentDidMount method by this time, so no chance of having products their
Solution to your problem:
Once an action is dispatched and which has become async due to Saga, you won't be able to get value in constructor, if you use Saga. You can just directly call upon the API using axios/fetch library in componentDidMount and await their (Making it synchronous). Once you get response, you may proceed further
In case you have functional component, then you may use Effect hook and bind the dependency to products state. You can write your code in this block, what you want to be executed after API call is made and product list modifies.
React.useEffect(
() => {
// You code goes here
},
[products]
);
You just have to console props rather than doing this.props. You should not reference props with this inside the constructor.
Do this instead:
console.log(props)
Middleware is not related to react lifecycle at all, other than it updates and connected components "react" to props updating.
Check the constructor docs
https://reactjs.org/docs/react-component.html#constructor
Question: why are you trying to log props in the constructor anyway? If you want to know what the props are, use one of the lifecycle functions, componentDidMount/componentDidUpdate, don't use the render function to do side-effects like make asynchronous calls or console log.
componentDidMount() {
console.log(this.props);
}
If you must log props in the constructor though, access the props object that was passed as the component won't have a this.props populated yet.
constructor(props) {
super(props);
...
console.log(props);
}

How to save fetched data from server to component state using redux and redux-thunk?

In my react app I have component named profile, and I am fetching data from server and showing it inside that component. I am using redux and redux-thunk along with axios. With help of mapDispatchToProps function, i am calling redux action for fetching that data when component is mounted and saving it to redux state. After that, using mapStateToProps function i am showing that data on the screen via props. That works fine. Now I want to have possibility to edit, for example, first name of that user. To accomplish that i need to save that data to component state when data is fetched from server, and then when text field is changed, component state also needs to be changed. Don't know how to save data to component sate, immediately after it is fetched.
Simplified code:
const mapStateToProps = (state) => {
return {
user: state.user
}
}
const mapDispatchToProps = (dispatch) => {
return {
getUserData: () => dispatch(userActions.getUserData())
}
}
class Profile extends Component {
state:{
user: {}
}
componentDidMount (){
this.props.getUserData()
// when data is saved to redux state i need to save it to component state
}
editTextField = () => {
this.setState({
[e.target.id]: e.target.value
})
};
render(){
const { user } = this.props;
return(
<TextField id="firstName"
value={user.firstName}
onChange={this.editTextField}
/>
)
}
}
You can use componentDidUpdate for that or give a callback function to your action.
I will show both.
First lets see componentDidUpdate,
Here you can compare your previous data and your present data, and if there is some change, you can set your state, for example if you data is an array.
state = {
data: []
}
then inside your componentDidUpdate
componentDidUpdate(prevProps, prevState) {
if(prevProps.data.length !== this.props.data.length) {
// update your state, in your case you just need userData, so you
// can compare something like name or something else, but still
// for better equality check, you can use lodash, it will also check for objects,
this.setState({ data: this.props.data});
}
}
_.isEqual(a, b); // returns false if different
This was one solution, another solution is to pass a call back funtion to your action,
lets say you call this.props.getData()
you can do something like this
this.props.getData((data) => {
this.setState({ data });
})
here you pass your data from redux action to your state.
your redux action would be something like this.
export const getData = (done) => async dispatch => {
const data = await getSomeData(); // or api call
// when you dispatch your action, also call your done
done(data);
}
If you are using React 16.0+, you can use the static method getDerivedStateFromProps. You can read about it react docs.
Using your example:
class Profile extends Component {
// other methods here ...
static getDerivedStateFromProps(props) {
return {
user: props.user
}
}
// other methods here...
}

Best practice for making small changes in UI with React and Redux

I'm using Redux and React to load data from a web service which is working well. I'd like to make small non-webservice-based changes in the UI in response to an action. A simplified example:
class SmartComponent extends React.Component {
handleClick = (e) => {
// how to best handle a simple state change here?
}
render() {
const { displayMessage } = this.props
return (
<DumbComponent message={displayMessage}/>
<button onclick={this.handleClick}>Change Message</button>)
}
}
const mapStateToProps = state => {
// state variables linked in the reducer
}
export default connect(mapStateToProps)(SmartComponent)
let DumbComponent = ({ message }) => {
return ({message})
}
If I modify the state in SmartComponent, for instance, by using this.setState, the props of SmartComponent will not be automatically updated. I believe it's a React anti-pattern to directly modify the props of SmartComponent. Is the best way to update the message in DumbComponent to make an action creator and link it in the reducer? That seems a bit overkill for a simple message change.
Yes, you should link it to the reducer.
However this is not mandatory:
How to do it
One other way to do this would be to store the message in the state of the SmartComponent.
Beware about the fact that Redux is no longer the single source of truth for the message.
class SmartComponent extends React.Component {
constructor(props) {
super(props)
// Initialize state based on props
this.state = {
message: props.message,
}
}
componentWillReceiveProps(nextProps) {
// Handle state update on props (ie. store) update
this.setState({ message: ... })
}
handleClick = (e) => {
this.setState({ message: ... })
}
render() {
const { displayMessage } = this.state
return (
<DumbComponent message={displayMessage}/>
<button onclick={this.handleClick}>Change Message</button>)
}
}
const mapStateToProps = state => {
// state variables linked in the reducer
}
export default connect(mapStateToProps)(SmartComponent)
let DumbComponent = ({ message }) => {
return ({message})
}
Should you do it ?
If the data you display in this component can be completely isolated from the rest of your application, that is to say no dispatched action could modify it, and no other component need it, keeping this data in the store can be unnecessary.
I mostly use this method to perform optimistic updates to the view component without altering the store until new value is saved by the server.

infinite loop when dispatching in componentWillReceiveProps

I have a Profile component that is loaded by react-router (path="profile/:username") and the component itself looks like this:
...
import { fetchUser } from '../actions/user';
class Profile extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
const { username } = this.props;
this.fetchUser(username);
}
componentWillReceiveProps(nextProps) {
const { username } = nextProps.params;
this.fetchUser(username);
}
fetchUser(username) {
const { dispatch } = this.props;
dispatch(fetchUser(username));
}
render() {...}
}
export default connect((state, ownProps) => {
return {
username: ownProps.params.username,
isAuthenticated: state.auth.isAuthenticated
};
})(Profile);
And the fetchUser action looks like this (redux-api-middleware):
function fetchUser(id) {
let token = localStorage.getItem('jwt');
return {
[CALL_API]: {
endpoint: `http://localhost:3000/api/users/${id}`,
method: 'GET',
headers: { 'x-access-token': token },
types: [FETCH_USER_REQUEST, FETCH_USER_SUCCESS, FETCH_USER_FAILURE]
}
}
}
The reason I added componentWillReceiveProps function is to react when the URL changes to another :username and to load that users profile info. At a first glance everything seems to work but then I noticed while debugging that componentWillReceiveProps function is called in a infinite loop and I don't know why. If I remove componentWillReceiveProps then the profile doesn't get updated with the new username but then I have no loops problem. Any ideas?
Try adding a condition to compare the props. If your component needs it.
componentWillRecieveProps(nextProps){
if(nextProps.value !== this.props.value)
dispatch(action()) //do dispatch here
}
Your componentWillReceiveProps is in an infinite loop because calling fetchUser will dispatch an action that will update the Props.
Add a comparison to check if the specific prop changes before dispatching the action.
EDIT:
In React 16.3+ componentWillReceiveProps will be slowly deprecated.
It is recommended to use componentDidUpdate in place of componentWillReceiveProps
componentDidUpdate(prevProps) {
if (this.props.params.username !== prevProps.params.username) {
dispatch(fetchUser(username));
}
}
See https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#fetching-external-data-when-props-change
If you have react routes with some path params like profile/:username,
You can simply compare the props.location.pathname
componentWillReceiveProps(nextProps){
if(nextProps.location.pathname !== this.props.location.pathname){
dispatch()
}
}

Resources