1

I have a state that specify which component render(component A or B). This state is determined when my action dispatch specific type(for example GO_TO_B or GO_TO_A).

Then I need to fetch some config from server to render component A. I want these config be in store.So I should call a action(for example fetchConfig() ) to async fetch data from server and dispatch response.

My question is that where i call the fetchConfig() action.

if I call this action in componentDidMount() in component A the error occur that cannot dispatch middle of dispatch.

So which method in react life cycle call after dispatch process and before render ?

mahdi jirofti
  • 81
  • 1
  • 6
  • When you say, "If I call action in componentDidMount()" you mean, If you dispatch action in `componentDidMount()`? If so, please share code, there might be something wrong happening. I do that most of the time and it usually works, unless otherwise. – ArchNoob Aug 13 '17 at 13:43

2 Answers2

0

You can use componentWillMount : Doc.

componentWillMount() is invoked immediately before mounting occurs. It is called before render(), therefore setting state synchronously in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method.

Piyush Dhamecha
  • 1,485
  • 1
  • 13
  • 22
0

I understand you are using redux.
If that's correct, i recommend to do your fetching with a thunk.

redux-thunk is a middleware that allows you to dispatch functions (instead of serialized objetcs like actions), that way you can deley a dispatch of an action or even dispatch it conditionaly.

An example of a thunk would be like that:

function loadSomeThings() {
    return dispatch => {
        fetchFirstThingAsync.then(data => { // first API call
            dispatch({ type: 'FIRST_THING_SUCESS', data }); // you can dispatch this action if you want to let reducers take care of the first API call
            return fetchSecondThingAsync(data), // another API call with the data received from the first call that returns a promise
        })
        .then(data => {
             dispatch({ type: 'SECOND_THING_SUCESS', data }); // the reducers will handle this one as its the object they are waiting for
        });
    };
}  

You can notice we can even chain ajax requests and we can dispatch (if we want) an action on each success (OR FAIL!).

I recommend reading the docs to understand it better.

Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99