How to Thunk

Scott Keplinger
3 min readDec 19, 2020

--

After learning so much about React, I know that upon first impression, Redux can seem like more trouble than it’s worth. It all depends on your particular app’s size and scope of course, and certainly there’s a lot of value in the option that keeps your components as simple as possible by maintaining data in your store. The problem that you’ll hit soon enough regards where that data originates from, if we need to fetch from an API, keeping that request asynchronous throws a wrench in our effort to keep components free of unnecessary logic. This is where we would want to utilize the Thunk middleware provided by Redux.

Screenshots from my dungeon game “Bork” for reference.

So with our typical setup, we’ll have our store dispatch a specific action to our reducer, which will in turn update our state and cause our relevant components to rerender. We’ll have problems if we drop our fetch directly into the action creator because the fetch will perform asynchronously and the creator function will try to return before the promise receives its fetched data. Depending on the size of the get request, the fetch may also take a while to resolve. We can use Thunk to address these concerns.

The primary utility that Thunk provides is it allows our action creator function to return another function instead of a normal JS object.

First, enable Thunk with applyMiddleware() in index.js when you create your app’s store

Next, we can call on a fetch action that we’ve separated from our main App component. Use connect to link to the store, and include your imported action.

This fetch action function will possess two distinct dispatches, the first (above) will hit a switch statement in our reducer (below) and set a state value that indicates that a fetch is loading or being requested. This will give us something to render while we wait for the fetch to resolve.

Next we will initiate the fetch call, and it is here that we may insert our second dispatch to called asynchronously within the .then().

Only after the fetch’s promise is fulfilled will this second dispatch hit our reducer, where our store will finally be updated with our new data.

--

--

Scott Keplinger
Scott Keplinger

No responses yet