0
votes

I use react, redux, and redux-thunk middlewere.

My code looks like :

  function thunkFunction(){
  return(dispatch) => { 
    dispatch(toggleSmth(false));
    dispatch(toggle2Smth(false));

    SomeService.getSmth()
    .then(response => {

      dispatch(oneMoreAction);
      dispatch(one2MoreAction);

    }
  }
}

And now I dispatch that whole thunk action after componenDidMount() in some component.

It works like that :

  1. dispatch(toggleSmth(false));
  2. dispatch(toggle2Smth(false));
  3. Promise to callback queue (not doing .then elements)
  4. } going to the close curly bracket
  5. Component reender
  6. going to .then(
  7. dispatching(oneMoreAction)
  8. Automatically component reender (WHY!?)
  9. back to the second dispatch -> dispatching(one2MoreAction)
  10. Another automatically component reender (WHY!?)

The question is :

Why once the dispatch wait for whole stack to clear. And in Promise after dispatch component is automatically reendered and after that it backs to the next Promise function element ?

In addition when I put dispatch(toggleSmth(false)) inside of promise like that :

function thunkFunction(){=
  return(dispatch) => { 
    SomeService.getSmth()
    .then(response => {

      dispatch(toggleSmth(false));
      dispatch(toggle2Smth(false));
      dispatch(oneMoreAction);
      dispatch(one2MoreAction);

    }
  }
}

The dispatch(toggleSmth(false)) and dispatch(toggle2Smth(false)) automatically reender component. (Not wait for clear the callback stack '}'). And after reender goes next -> to first dispatch(oneMoreAction);

Why once dispatching causing automatically reender and once you have to wait for execution of element inside of function ?

1
But once it works like you said and once doesn'tPatryk Janik

1 Answers

0
votes

I think you have a little misunderstanding about 2 things:

  • The react component life cycle
  • The way thunk actually works.

What is going on, at the most basic level, is you are calling a thunk action (a proimise) which calls dispatch 4 times in total. Every time you call an action that modifies the state, the components touched by that state (via mapStateToProps) will re-render.

When you put all of the dispatch functions under 1 async call (i.e nested once) (SomeService.getSmth().then(() => {...});) in this case) it causes those to fire synchronously relative to each other... the component still re-renders though because it is touched by a state that is being modified.

In the first case, the 2 dispatch's are called synchronously relative to each other, then the service call happens along with the other two dispatches only after the service call finishes