Setting up redux thunk in react.js

blog

Anjali Agnihotri

CSMS

What is Thunk?

  • The past tense of thought is thunk. Hahaha, 😁 Jokes apart.

  • Your redux operations, such as API requests, can now exhibit asynchronous behavior thanks to redux-thunk.

  • A middleware called Redux Thunk enables you to call action creators that give back functions rather than action objects.

Redux Flow Without Thunk

Redux flow with Thunk

Step 1 - Installation and setup

Running the following command will install redux-thunk:


    

npm install redux-thunk

Step 2 - Implement redux-thunk to Redux Middleware


    

import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; ... export const store = createStore(countReducer, applyMiddleware(thunk))

Step 3- Dispatch a Function rather than an Object

We can only dispatch objects with a type property without redux-thunk. We are able to return functions using this middleware. We can do async calls (that is, API calls) within the routines either before or after we dispatch actions.

src/count/container.js


    

const ABC = dispatch => { return { handleIncrClick: () => dispatch( innerDispatch => innerDispatch({ type: 'INCREMENT' }) ), handleDecrClick: () => dispatch({ type: 'DECREMENT' }) } };

All of the actions should be refactored into a separate file just for this container (actions.js). The operations may be located anywhere.

src/counter/actions.js


    

export const incrasync = innerDispatch => innerDispatch({ type: 'INCREMENT' })

src/count/container.js


    

import { incasync } from './actions'; ... handleIncrClick: () => dispatch(incrasync); ...

Why do we need redux-thunk?

It enables us to have redux operations return functions rather than objects. Simple synchronous updates can only be made by dispatching actions in plain redux, which does not support complicated logic inside action functions. This middleware broadens its functionality and enables you to create intricate logic that communicates with the store.

productMangerImage
Anjali Agnihotri
Frontend Developer

Hey, myself Anjali Agnihotri. I'm a Frontend Developer at Nimblechapps. I'm a fun-loving, multi-tasker person and person who loves to code and learn new languages.

productMangerImage

Related Post

CSMS
200 Views

Update multiple components on props change in react js

What are Props? The value of a tag's attributes is kept in the props type of object in ReactJs. The name "props" indicates "properties,"...

200 Views
blog

Hemal Halapani

CSMS
512 Views

How Nimblechapps acquired ISO Certification?

Why did we want to get certified? The International Organization for Standardization (ISO) certification creates credibility and...

512 Views
blog

Kalrav Vaidya

CSMS
356 Views

Top 3 free alternatives of Postman

The very first question we raise here is, What is a Postman actually? As we all know, Postman is an API platform for building and testing...

356 Views
blog

Kavita Purohit