Alexander Solonik
Alexander Solonik

Reputation: 10230

Why are action function called wrapped inside dispatch in react?

I was just going through some react-redux code online and basically i came across the following set of code , which is basically a js file full of ACTIONS , just to give some context a combination of redux and redux-thunk is being used here:

export const init = () => async dispatch => {
  dispatch({ type: TYPES.SET_LOADING });
  await dispatch(getConfig());
  await dispatch(getGenres());
  dispatch({ type: TYPES.REMOVE_LOADING });
};

// Action Creator to get the config object from the API
export const getConfig = () => async dispatch => {
  const res = await tmdbAPI.get('/configuration');
  dispatch({
    type: TYPES.GET_CONFIG,
    payload: res.data,
  });
};

I am a bit confused as to why is getConfig function is being wrapped inside a dispatch ?

Upvotes: 1

Views: 616

Answers (2)

syjsdev
syjsdev

Reputation: 1336

if you don't want, don't wrap that like this

export const init = () => async dispatch => {
  dispatch({ type: TYPES.SET_LOADING });
  dispatch(await getConfig());
  dispatch({ type: TYPES.REMOVE_LOADING });
};

//this is not using redux-thunk

// Action Creator to get the config object from the API
export const getConfig = async () => {
  const res = await tmdbAPI.get('/configuration');
  return {
    type: TYPES.GET_CONFIG,
    payload: res.data,
  };
};

Important
but there are so many reasons why wrap the actions by dispatch.

Here is one example.

when you want get multiple data in one action step by step

export const getData = () => async dispatch => {
  dispatch({
    type: DATA_LOADING_START
  });
  try {
    const res = await tmdbAPI.get('/url1');
    dispatch({
      type: DATA1_LOADED,
      payload: res.data,
    });
    const res = await tmdbAPI.get('/url2');
    dispatch({
      type: DATA2_LOADED,
      payload: res.data,
    });
  } catch (err) {
    // handle error
  }
  dispatch({
    type: DATA_LOADING_END
  });
};
//this is using redux-thunk

@AlexanderSolonik
Question: Why wrap actions by dispatch?

because dispatch() sends the action result to the reducer. enter image description here

Upvotes: 1

Travis James
Travis James

Reputation: 1939

Redux thunks are just redux actions that can perform side effects. So

export const init = () => async dispatch => {
  dispatch({ type: TYPES.SET_LOADING });
  await dispatch(getConfig());
  await dispatch(getGenres());
  dispatch({ type: TYPES.REMOVE_LOADING });
};

Is just an async init function which when called performs the steps in a synchronous manner.

The key is that thunks can dispatch other thunks/actions/etc so the init thunk is just dispatching the getConfig() action which is itself async so the next step of the init function won't be performed until the config API call finishes (possibly because some other code depends on it)

Upvotes: 0

Related Questions