0
votes

I have an isomorphic react application using redux,react-router, react-router-redux, I want to bind my components with url query params and when the query params changed, send request to an API and update my state and finally fetch data. I know with react-router-redux it automatically update my state. Also I want to show a pre-loader (spinner) to user when data is fetching. what is the best way to write an action creator for this issue ? thanks

1

1 Answers

0
votes

I want to show a pre-loader (spinner) to user when data is fetching

Pass a data prop to your component. When it's undefined, show a spinner.

const MyComponent = (props) => {
  if (!props.data) return <Spinner />
  ...
}

When the query params changed, send request to an API and update my state and finally fetch data

The most simple solution (this can get quite complex depending on your needs) is to fire this logic on the Component's lifecycle hooks.

When the route changes react-router, with a typical configuration, will cause the component to render if you were previously on a different route, and update if you were previously on the same route (i.e. the same path, but with different query params).

So for the first case, use componentDidMount, for the second case, use comonentDidUpdate(prevProps, prevState) lifecycle hook.

To map the asynchronous API call to redux action(s), use a library like redux-thunk or probably more tailored to this use case, redux-promise-middleware. How to use those is a bit deep in scope for me to go into here, but they both have excellent documentation.

In the end, you'll want to map those actions in a reducer put the response data somewhere in your state tree, then using react-redux bind that location in the state tree to the data prop on your Component, as I mentioned before.