score:3

Accepted answer

The problem is you return a function NOT a promise.
This resolves immediately.

See working code sample

export const fetchData2 = dispatch => () => {
  dispatch({type: 'START_FETCH'})
  const p = [
    fetchDataSetOne(dispatch),
    fetchDataSetTwo(dispatch)
  ];
  Promise.all(p).then((res) => setHasLoaded(res));
};

// this returns a promise AFTER it calls an action
const fetchDataSetOne = dispatch => {
  return axois.get(`${API_URL}/dataSetOne`).then(res => {
    dispatch({
      type: "FETCH_ALL_DATA_SET_ONE",
      payload: res.data.docs
    });
  });
};

This resolves after both promises are resolved, but the state updates after each promise is resolved. To update state after all promises resolve, try this:

export const fetchData3 = dispatch => () => {
  dispatch({ type: "START_FETCH" });
  const p = [
    axois.get(`${API_URL}/dataSetOne`),
    axois.get(`${API_URL}/dataSetTwo`)
  ];
  Promise.all(p).then(callActions(dispatch));
};

const callActions = dispatch => res => {
  dispatch({
    type: "FETCH_ALL_DATA_SET_ONE",
    payload: res[0].data.docs
  });
  dispatch({
    type: "FETCH_ALL_DATA_SET_TWO",
    payload: res[1].data.docs
  });
  setHasLoaded(res);
};


Related Query

More Query from same tag