Asynchronous Action Creators
Learn about the async action creators in server communication.
Let’s start by looking at a server communication implementation with async action creators using the redux-thunk
library to understand the underlying pitfalls of this approach:
const fetchUser = id => dispatch =>
axios.get(`http://api.ourserver.com/user/${id}`)
.then(({ data: userData }) => dispatch(setUserData(userData)));
Consider another example where we would like to fetch a list of comments for a user:
const fetchComments = id => dispatch =>
axios.get(`http://api.ourserver.com/user/${id}/comments`)
.then(({ data: commentsData }) => dispatch(setComments(commentsData)));
Even without the more complex functionality mentioned earlier, the code contains many duplications between action creators. And there are a few other problematic issues:
- We can’t log actions before the network request completes, preventing the regular Redux debug flow.
- Every action creator has repetitive functionality for handling errors and setting headers.
- Testing gets more challenging as more async action creators are added.
- If we want to change the server communication strategy (e.g., replace
axios
withsuperagent
), we need to change multiple places in the codebase.
Get hands-on with 1200+ tech skills courses.