The most common question I hear post intro to redux is: "How do I fetch some data in actions?"
Most of them would hit the roadblock with: Actions must be plain objects. Use custom middleware for async actions.
that is because Actions are meant to be plain JavaScript objects and must have a type
property that indicates the type of action being performed.
Let us see a quick example to make an API request say this xkcd comic API.
As there is no community consensus for handling async actions and there are many libs out there that will make things easier in handling async actions, but in this example below we shall take the vanilla approach.
Let us start with an initial state that looks like:
1 2 3 4 5 |
|
a reducer
which handle fetching
, fetched
and failed
states of the action.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
a store
and dispatch
based on the flow:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
Some mandatory render
method (not react this time ;))
1 2 3 4 5 |
|
Working code:
Some interesting discussions:
So, explaining async actions in Redux to a friend, what do you suggest?
— Hemanth.HM (@GNUmanth) February 15, 2018
0. Talk about Thunk/Promise middlewares for Redux?
1. Do something more vanilla like below?
2. Cases where a middleware would be mandatory? pic.twitter.com/hOW6KG6l7B
P.S: Thanks to <GreenJello>
on the quick review.