Blog>
Snippets

Async Actions with Redux Thunk using async/await

Show how to create a Redux thunk action using the modern async/await syntax to fetch data from an API and dispatch actions to the store.
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

// Define action constants
const FETCH_DATA_BEGIN = 'FETCH_DATA_BEGIN';
const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
const FETCH_DATA_FAILURE = 'FETCH_DATA_FAILURE';

// Action creators
const fetchDataBegin = () => ({
  type: FETCH_DATA_BEGIN
});

const fetchDataSuccess = data => ({
  type: FETCH_DATA_SUCCESS,
  payload: { data }
});

const fetchDataFailure = error => ({
  type: FETCH_DATA_FAILURE,
  payload: { error }
});
This piece of code includes the necessary imports for creating a Redux store and applying the thunk middleware. It defines the Redux action types and creators for three states of an async action: when the fetch begins, succeeds, or fails.
const initialState = {
  items: [],
  loading: false,
  error: null
};

// Reducer handling the actions
function rootReducer(state = initialState, action) {
  switch (action.type) {
    case FETCH_DATA_BEGIN:
      return {
        ...state,
        loading: true,
        error: null
      };
    case FETCH_DATA_SUCCESS:
      return {
        ...state,
        loading: false,
        items: action.payload.data
      };
    case FETCH_DATA_FAILURE:
      return {
        ...state,
        loading: false,
        error: action.payload.error,
        items: []
      };
    default:
      return state;
  }
}
This is the reducer that handles actions dispatched by the Redux thunk. It updates the state based on whether the data fetching is starting, successful, or failed.
export function fetchData() {
  return async dispatch => {
    dispatch(fetchDataBegin());
    try {
      const response = await fetch('https://api.example.com/data');
      const data = await response.json();
      dispatch(fetchDataSuccess(data));
    } catch (error) {
      dispatch(fetchDataFailure(error));
    }
  };
}
This function is a Redux thunk action. It makes an asynchronous API call using fetch. Dispatches actions to signal the beginning of the fetch, then either the success or failure of the fetch depending on the result of the API call.
const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

// Dispatch the fetchData thunk action
store.dispatch(fetchData());
This code snippet creates the Redux store, applies the Redux Thunk middleware, and demonstrates how to dispatch the thunk action 'fetchData' which initiates the async process.