How to create reusable async thunk without unnecessary render

Viewed 93

I have the two following Redux actions (thunk)

export const getA = () => async (dispatch, getState) => {
  const response = await http.get('/get-a');
  return dispatch({ type: 'FETCHED_A', payload: response });
}

export const getB = () => async (dispatch, getState) => {
  const response = await http.get('/get-b');
  return dispatch({ type: 'FETCHED_B', payload: response });
}

Where each one can be used separately and works well.

And when I want to use them asyncronously I using the following action:

export const getAll = () => async (dispatch, getState) => {
  await Promise.allSettled([ dispatch(getA()), dispatch(getB()) ])
}

Which works well, but when I use it, the component renders twice (once for every dispatch in Promise), how can this code be updated to remove the not necessary render? (But so that functions can be still reused separately).

I thought about a chaining solution, but I haven't figured out how to get it work, because I can't pass an object as an action, so I am not sure if it is possible at all.

Aobj.fetch().dispatch();
Bobj.fetch().dispatch();

And async fetch, something like:

Promise.allSettled([Aobj.fetch(), Bobj.fetch()])
.then(response => {
  dispatch({ type: 'ALL_FETCHED', payload: response })
})

PS: This code is a simplified code for example only, to increase my chances of being understood

2 Answers

Try to use batch:

  import { batch } from 'react-redux';

  const test = () => {
    batch(() => {
      dispatch(getA);
      dispatch(getB);
    });
  };

Well, is the same component consuming both fetched data? because if so then it's correct that it renders twice because the redux state gets updated twice.

Related