A
A
alex4answ2020-12-21 14:37:28
React
alex4answ, 2020-12-21 14:37:28

Sequential dispatch of asynchronous actions?

Good afternoon, I ran into a problem:

You need to display data from 2 different (but related) parts of the store into the component.
But before the output, the data needs to be updated.

Example:
there are Houses (coordinates, etc.), and there is a History of Houses (who lived when, etc.), the store structure:
- houses
- - houses
- - histories ( WeakMap )

As a result, before displaying the page, I need to first request all Houses, and then for all these houses, request History.

How to do it?
I understand that you can combine this into 1 action, but I don’t want to (because the data will be mixed up, it will be difficult to work with them)

How to first dispatch the loading of houses in useEffect, and after loading, dispatch the loading of stories to these houses?

something like:

const dispatch = useDispatch();
const houses   = useSelector((state) => state.houses.houses);
const housesHistory = useSelector((state) => state.houses.histories);

useEffect(() => {
  dispatch(getHouses());
  dispatch(getHousesHistory(houses));
}, [dispatch, houses, housesHistory])


But obviously this does not work, as actions are sent one after another, do not wait for loading, etc., and also an endless update, because useEffect's dependencies are not correct, but not the point.

How to make sequential redux requests?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Lewandowski, 2020-12-21
@alex4answ

Like this:

// запрашиваете дома при маунте компонента.
useEffect(() => {
  dispatch(getHouses());
}, [dispatch]);

// запрашиваете историю при изменении houses.
useEffect(() => {
  dispatch(getHousesHistory(houses));
}, [dispatch, houses]);

But it’s better not to keep such logic in components, but to take it out into something like redux-saga.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question