Blog>
Snippets

Implementing Redux Middleware for Async Actions

Demonstrate how to use Redux middleware, like redux-thunk or redux-saga, to handle asynchronous actions within a Redux flow.
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

const initialState = {};

// Reducer function
function rootReducer(state = initialState, action) {
  switch(action.type) {
    case 'FETCH_DATA_SUCCESS':
      return { ...state, data: action.payload };
    default:
      return state;
  }
}

// Async action creator using redux-thunk
function fetchData() {
  return dispatch => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => dispatch({ type: 'FETCH_DATA_SUCCESS', payload: data }))
      .catch(error => console.error('Fetching data failed', error));
  };
}

// Creating Redux store with middleware
const store = createStore(rootReducer, applyMiddleware(thunk));
This code demonstrates setting up a Redux store with redux-thunk middleware for handling asynchronous actions. It includes an async action creator function 'fetchData' that fetches data from an API and dispatches a success action with the fetched data. The rootReducer manages the state based on the dispatched action. The createStore function is used to create the Redux store with applied thunk middleware, allowing asynchronous actions within the Redux flow.