Blog>
Snippets

Integrating Redux Thunk with Next.js API Routes

Provide an example of dispatching Redux Thunk actions from Next.js API Routes to handle asynchronous operations like fetching data.
// store.js
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers'; // Import your root reducer

const makeStore = (initialState) => createStore(
  rootReducer,
  initialState,
  applyMiddleware(thunk)
);

export default makeStore;
This is the Redux store configuration which applies the thunk middleware to allow writing functions with logic inside that can interact with the Redux store.
// actions.js
// Action type
export const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';

// Synchronous action creator
const fetchDataSuccess = (data) => ({
  type: FETCH_DATA_SUCCESS,
  payload: data
});

// Asynchronous thunk action creator
export const fetchData = () => async (dispatch) => {
  try {
    const response = await fetch('/api/data'); // Replace with your actual API
    const data = await response.json();
    dispatch(fetchDataSuccess(data));
  } catch (error) {
    console.error('An error occurred while fetching data:', error);
  }
};
This file defines an asynchronous thunk action creator which fetches data from an API and dispatches a synchronous action to update the Redux store once the data is successfully retrieved.
// api/data.js (Next.js API route)
import { wrapper } from '../../store'; // Import the store wrapper
import { fetchData } from '../../actions'; // Import the thunk action creator

export default wrapper.getServerSideProps(async ({ store }) => {
  await store.dispatch(fetchData());
  return { props: {} }; // Return empty props as this is an API route
});
In the Next.js API route, we dispatch the thunk action creator using 'getServerSideProps' function provided by Next.js, which runs on the server before the page is rendered. The dispatched action fetches the required data and updates the store.