In my program I recently learned about Thunk. Thunk is middleware for Redux that allows you to return a function from your action creator instead of an action. This allows you to dispatch multiple actions to your reducer which comes in handy when working with asynchronous requests, which as we know can take various amounts of time. A dispatch can be made when the initial event triggers it and another can be made when the data from the request becomes available.
Here is an example:
const fetchAstronauts= () => {
return (dispatch) => {
dispatch({ type: 'LOADING_ASTRONAUTS' });
fetch('http://api.open-notify.org/astros.json')
.then(response => response.json())
.then(json => dispatch({ type: 'ADD_ASTRONAUTS', astronauts: json.people }));
};
}
Here, the fetchAstronauts function is an action creator that returns a function with dispatch being passed as a parameter. When dispatch is mapped to props, you can add the function as a prop to be called by dispatch like so:
const mapDispatchToProps = dispatch => {
return {
fetchAstronauts: () => dispatch(fetchAstronauts())
}
}
Then, when your component mounts, you can call componentDidMount to make the asynchronous request to the API and update your redux store like so:
componentDidMount() {
this.props.fetchAstronauts();
}
To go over the previous code, when the component mounts, the prop fetchAstronauts will be called, triggering a call to dispatch with our action creator being called as the argument. Our action creator will first dispatch an action with type: 'LOADING_ASTRONAUTS' to our reducer, and then once our astronaut data becomes available, another action will be dispatched to the reducer with the payload of astronaut data. This data can be used to update your state however you would like within your reducer.
Additionally, Thunk can be used to conditionally dispatch an action. Here is an example from the documentation:
function incrementIfOdd() {
return (dispatch, getState) => {
const { counter } = getState();
if (counter % 2 === 0) {
return;
}
dispatch(increment());
};
}
Here, the function is only dispatching an action to the reducer if the counter property in state is odd. Very useful!
To wrap it up, I think Thunk is pretty great, in that it makes it simple to change how we dispatch actions to our reducer. All in all, this is achieved by wrapping our action creator in a function that has access to dispatch.
Let me know if you have any other good uses for Thunk or any other middleware I should read up on. Thanks for reading!
Top comments (2)
Wow..! Simple and elegant
Thank you Anshul!