I'm building an application where I need to fetch the initial redux sate from the server before my main component mounts. In my actions, I used redux-thunk to get the necessary data:
export const getInitialStateSuccess = (state: any): IfetchThemeSuccess => {
console.log('state', state);
return {
type: FETCH_INIT_STATE,
state
};
};
// here I fetch the data from the server and call getInitialStateSuccess
// to pass it to redux init state
export const getInitialState = () => {
return (dispatch: any) => {
api.getInitState().then((data) => {
dispatch(getInitialStateSuccess(data));
});
};
}
However, I do not know where I should call getInitialState(). I need to initialize the state of the app before the main component mounts. Do you think it would be a good practice to call this action in componentWillMount? It has to be called only once. Please let me know if the approach I'm describing above is a good practice or not. Thanks!
You can call it in WillMount but DidMount is preferred. This is because WillMount can be called twice if you have server-side rendering.
Either way, you're going to need a intermediary "loading" screen before hand since the call is asynchronous, and it is going to render before data has loaded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With