Thunking a bit too long - abukhalil-LTUC-ASAC/amman-401d4 GitHub Wiki
Redux Async
There is one aspect that redux could handle, async actions. So far we have not implemented any and all actions were on that single thread of V8 engine.
One quick way is to write in isFetching
flag into the state, this allows for the dispatch to handle two extra data streams, one for when the async action is started, and one when the data or timeout returns/finishes.
state = {
isFetching: false,
didInvalidate: false,
items: []
},
Redux Thunk
Once the action is executed, what is called is actually an action creator function, which is different than the action object we used before. This allows for the use of dispatch middlewares that was not possible before, one of these middlewares is the Thunk
.
This allows for impure function calls such as ajax, and other side effect riddled operations. A typical function creator looks like:
export const RECEIVE_POSTS = 'RECEIVE_POSTS'
function receivePosts(subreddit, json) {
return {
type: RECEIVE_POSTS,
subreddit,
posts: json.data.children.map(child => child.data),
receivedAt: Date.now()
}
}
Other uses
One of the other operations that are not necessarily async, but is better used by the Thunk
is logging operations. What you'd think a simpler way is to call the console.log
for the data at every action function? This looks unscalable though, how about the tons of different solutions available with monkeying around? Might as well pass in a middleware to handle this problem, and done.
Lessons learned
- How far should you reduce your reducers?. Unless there are special operations, general action handling is best.
- Is it a good or bad thing to have combined or separate reducers I'd go for combined whenever I am alone, but for separated work its is better to have multiple different reducers using the same action from within to ease customizability with little conflict as possible.