Blog>
Snippets

Updating Redux Middleware for Async Actions

Show how to update existing middleware to handle async actions using the new Redux v5.0.0 approach.
import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';

// An example of a simple reducer
const rootReducer = (state = {}, action) => {
  switch (action.type) {
    case 'DATA_LOADED':
      return { ...state, data: action.payload };
    default:
      return state;
  }
};

// Apply the middleware to the store
const store = createStore(
  rootReducer,
  applyMiddleware(thunkMiddleware)
);

// Now you can dispatch async actions that return a function instead of an object
store.dispatch((dispatch) => {
  fetch('/my-api-endpoint')
    .then(response => response.json())
    .then(data => dispatch({ type: 'DATA_LOADED', payload: data }))
    .catch(error => console.error('Error loading data: ', error));
});
This code demonstrates how to integrate thunk middleware into a Redux store to handle asynchronous actions. The `thunkMiddleware` allows you to write action creators that return a function instead of an action object. The function can be used to perform asynchronous operations such as API calls, and then dispatch an action when the operation completes.
import { configureStore } from '@reduxjs/toolkit';

// An example of a simple reducer
const rootReducer = (state = {}, action) => {
  switch (action.type) {
    case 'DATA_LOADED':
      return { ...state, data: action.payload };
    default:
      return state;
  }
};

// Use Redux Toolkit's configureStore to set up the store with Redux Thunk
const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(thunkMiddleware),
});

// You can then use the store as usual, dispatching async thunks as needed.
This snippet uses Redux Toolkit's `configureStore` method to set up the store, which by default includes `thunkMiddleware`. The `configureStore` method simplifies the store setup process, including middleware configuration. The `getDefaultMiddleware` function includes other recommended middleware by default, and you can concatenate additional middleware like `thunkMiddleware` if you need.