0
votes

I'm using redux with React to manage states but when I called two dispatch function from one action creator, it's return state from the first dispatch but unable to get updated state after another dispatch call.

I've tried to call dispatch from different reducers and tried to call after API call.

Here are my actions.

export const setLoader = (loader) => dispatch => {
  dispatch({ type: SET_LOADER, payload: loader });
};

export const fetchCategory = (setLoader) => async dispatch => {
    setLoader(true);
    try {
        const instance = axios.create();
        instance.defaults.headers.common['Authorization'] = AUTHORIZATION_TOKEN;
        const response = await instance.get(API_PATHS.SERVICE_CATEGORY_API);

        dispatch({ type: FETCH_CATEGORY, payload: response.data });

    } catch (e) {
      setLoader(false);
    }

};

Here i defined reducers:

export default (state = INITIAL_STATE, action) => {

    switch (action.type) {
    case FETCH_CATEGORY:
        return { ...state, categoryList: action.payload };
    case SET_LOADER:
        return { ...state, isLoading: action.payload };
    default:
        return state;
    }
};

Here my component connected with redux:

const mapStateToProps = state => {
  return ({
      categoryList: state.locator.categoryList
  });
}

export default connect(
    mapStateToProps,
    { fetchCategory, setLoader }
)(ServiceLocator);

I expect the output to return updated categoryList, but the actual it returns a blank array.

1

1 Answers

0
votes

You are performing an asynchronous task in your action creator, which Redux can't handle without a middleware. I recommend using the middleware redux-thunk. This will allow you to perform asynchronous actions in your action creators and dispatch multiple times.

Hope this helps!


UPDATE:

If you have the redux-think middleware installed and added to Redux (per your comment), then next I would look at setLoader() - it looks like that function is curried and I don't think you want it to be. I would remove the setLoader() step and dispatch that action directly from fetchCategory():

export const fetchCategory = () => async dispatch => {
  dispatch({ type: SET_LOADER, payload: true });
  try {
    const instance = axios.create();
    instance.defaults.headers.common['Authorization'] = AUTHORIZATION_TOKEN;
    const response = await instance.get(API_PATHS.SERVICE_CATEGORY_API);

    dispatch({ type: FETCH_CATEGORY, payload: response.data });

  } catch (e) {
    dispatch({ type: SET_LOADER, payload: false });
  }
};