Redux and Thunk

Seth Blanchard
2 min readJul 28, 2021

Thunk is a wonderful package that is able to be incorporated into one’s React/Redux application and fixes a problem that one can have when attempting to bridge the gap between asynchronous fetch calls to the external API and the synchronous actions one creates while using Redux.

Thunk is middleware that is applied to your Redux store upon instantiation. Usually placed in the Index.js file, it is initially imported with the following lines of code…

import {createStore, applyMiddleware, compose, combineReducers} from 'redux';import thunk from 'redux-thunk';

The first import allows us to utilize createStore, which takes a reducer (in this case, I utilized a “rootreducer” which combined all of my separate reducers into one reducer) and then applyMiddleware. Thunk is passed into the latter.

let theStore = createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)))

So here’s the use case and why middleware like Thunk is so useful. The below is an example of a typical fetch to the backend API.

export function fetchProducts() {
const products = fetch('http://localhost:3000/api/v1/products'
;
return {
type: 'ADD_PRODUCTS',
products
};
};

At this point, our fetch is sent but, being asynchronous, the return will fire prior to the fetch coming back with data. This will then produce errors as there would be no data in the products variable. Enter Thunk…

export function fetchCarts(action) {
return (dispatch) => {
fetch('http://localhost:3000/api/v1/carts')
.then(resp => resp.json())
.then(carts => dispatch({
type: 'FETCH_CARTS',
payload: carts
}))
}
}

Thunk allows for a dispatch function to be returned in lieu of the fetch data. The fetch is then implemented and data along with the promise is returned. We then turn our JSON into and JS object. This JS object is then fed the dispatch which sends our action to our reducer. Thus allowing for an asynchronous Fetch to interact properly with the synchronous Redux actions.

--

--

Seth Blanchard
0 Followers

Full-Stack Software Developer- Founder of Skylark Hammocks, BEST, LLC, and several other as of yet unrealized ventures.