nl pkr
nl pkr

Reputation: 656

How to wait for data in redux

For example I have 2 components. In 1st I do async call on server and after dispatch action to put response in to redux store. In 2nd component I want to wait for the response come to store and after do some work.

1st component looks like

const response = await api.call(); // async call on server
dispatch(putToTheStore(response)); // put data to the store

2nd component looks like

await props.response; // here i want to wait data come to store

// and after it actually come to the store, do some work

Is it possible ?

Upvotes: 4

Views: 2972

Answers (1)

forrert
forrert

Reputation: 4199

If you connect your second component to the store using react-redux's connect function, you don't need to do anything explicit to update the component. The data you added to the store will simply be available to the component as a prop.

If you need to (synchronously) do some work on the loaded data, e.g. apply a filter, or do some sorting, I would recommend doing this directly in the mapStateToProps function, as this function is called automatically each time the store updates to calculate the new props for your component.

If you need to do some additional work in the second component, i.e. load more data based on the previous asynchronous call, you would need to implement the componentWillReceiveProps function.

Upvotes: 6

Related Questions