Learn

At this point, you are ready to use thunks to define asynchronous operations in Redux. But you may be curious about how redux-thunk works. In order to allow us to write action creators that return thunks in addition to plain objects, the redux-thunk middleware performs a simple check to the argument passed to dispatch. If dispatch receives a function, the middleware invokes it; if it receives a plain object, then it passes that action along to reducers to trigger state updates.

We’ve pasted the source code into your code editor so you can see it for yourself. And here’s a link to the project’s repo in case you’d like to explore further!

We won’t worry about the extraArgument option, so for our purposes, we can focus on thunk, the default export, which is equal to the function returned on line 2.

Recall getUser, the thunk action creator from the previous exercise:

const getUser = (id) => { return async (dispatch, getState) => { const payload = await fetchUser(id) dispatch({type: 'users/addUser', payload: payload}) } }

Suppose we were to call dispatch(getUser(7)) with the thunk middleware applied. We know that getUser(7) returns a thunk, so on line 3 of the thunk middleware, typeof action === 'function' will evaluate to true. On line 4, the middleware will then invoke getUser(7) with the arguments dispatch and getState. This invocation will initiate the asynchronous fetching performed by the thunk. When that asynchronous fetching is complete, the thunk will dispatch the synchronous action {type: ‘users/addUser’, payload: payload}.

For contrast, let’s walk through what happens when we dispatch that synchronous action. Since the action is a plain object, typeof action === 'function' will evaluate to false. The redux-thunk middleware therefore skips to line 7, and invokes the next middleware in the pipeline, passing the action along.

Instructions

Make sure you understand how redux-thunk works by reviewing the code editor’s provided redux-thunk source code. The key step happens where the middleware checks whether or not the action is a function:

if (typeof action === 'function') { //... }

If the action is a function (as happens when we dispatch thunks returned by thunk action creators), then redux-thunk invokes that function. If the action is not a function (as happens when we dispatch plain objects), redux-thunk passes it through to the next step in the middleware pipeline.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?