There is not necessarily an advantage to fetching data with Redux, but more of an advantage of knowing what is going on when using Redux to fetch data.
Almost always its going to be the exact same flow.
- We are going to render a component on the screen. Such as your
Posts
or PostList
component which needs to get a list of posts from the json api in order to show itself correctly. As a result I will define a componentDidMount()
method on a class. That is why I created PostList to be a class based component, to ensure I had access to lifecycle methods.
- Inside the
componentDidMount()
lifecycle method we are going to place an action creator. So anytime our component shows up on the screen the action creator will be automatically called.
- The action creator will have some code inside that will use axios or fetch, but in my case I prefer axios, to make the API request over to the json api.
- After the request is made, the api will respond with some amount of data. Once we get back the data,
- Our action creator will do what it always should do which is to return an action and the action object will have a fetch data on the payload property. We are going to return the action from an action creator and the dispatch method will dispatch that action and send it off to all the different reducers inside our app. We will have some specially configured reducer that will be watching for an action of type whatever we gave it. The reducer will see the action, pull off the data from the payload property.
- The reducer will run and produce a new state object and it will be sent off to the react side of the application. This will cause the react side of our application to be re-rendered with the json api data we got back. We can use the
mapStateToProps()
to get that json api data, lets say its a list of posts. We get it out of the global state object and into our component.
Some notes around each step.
Placing an action creator into a componentDidMount()
lifecycle method is a common practice. We want to ensure components themselves are responsible for data they need by calling an action creator usually from within a lifecycle method.
There are some other places where you can call an action creator to fetch data but that involves other libraries not mentioned here. The most common place will be the componentDidMount()
lifecycle method.
Regarding the action creators, we generally will ensure that action creators are responsible for making our API request. In some case you might put together some external class or service that is going to do the actual request for us, but in general its the action creator that will do the initial fetching of the api data. Enter stage left is Redux-Thunk.
Last thing, when you fetch data and get it into a component you always make use of the mapStateToProps function to get data from the redux store and into the component.