React Redux dispatch action after another action React Redux dispatch action after another action javascript javascript

React Redux dispatch action after another action


If you are using redux thunk, you can easily combine them.It's a middleware that lets action creators return a function instead of an action.

Your solution might have worked for you now if you don't need to chain the action creators and only need to run both of them.

this.props.onList(top, newSkip);this.props.onSetSkip(newSkip);

If you need chaining(calling them in a synchronous manner) or waiting from the first dispatched action's data, this is what I'd recommend.

export function onList(data) {  return (dispatch) => {          dispatch(ONLIST_REQUEST());    return (AsyncAPICall)    .then((response) => {      dispatch(ONLIST_SUCCESS(response.data));    })    .catch((err) => {      console.log(err);    });  };}export function setSkip(data) {      return (dispatch) => {              dispatch(SETSKIP_REQUEST());        return (AsyncAPICall(data))        .then((response) => {          dispatch(SETSKIP_SUCCESS(response.data));        })        .catch((err) => {          console.log(err);        });      };    }export function onListAndSetSkip(dataForOnList) {  return (dispatch) => {     dispatch(onList(dataForOnList)).then((dataAfterOnList) => {       dispatch(setSkip(dataAfterOnList));     });  };}


Instead of dispatching an action after a sync action, can you just call the function from the reducer?

So it follows this flow:

Sync action call --> Reducer call ---> case function (reducer) ---> case function (reducer)

Instead of the usual flow which is probably this for you:

Sync action call --> Reducer call

Follow this guide to split the reducers up to see what case reducers are.

If the action you want to dispatch has side affects though then the correct way is to use Thunks and then you can dispatch an action after an action.

Example for Thunks:

export const setSkip = (skip) => {    return (dispatch, getState) => {        dispatch(someFunc());        //Do someFunc first then this action, use getState() for currentState if you want        return {            type: 'LIST.SET_SKIP',            skip: skip        };    }};