Get started with redux-thunk CDN

MIT licensed

Redux Thunk: Middleware for asynchronous, complex actions in pure JS functions .

Tags:
  • redux
  • thunk
  • middleware
  • redux-middleware
  • flux

Stable version

Copied!

How to start using redux-thunk CDN


import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';

// Define the initial state
const initialState = {
  loading: false,
  data: [],
  error: null,
};

// Define the reducer
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'FETCH_DATA_REQUEST':
      return { ...state, loading: true };
    case 'FETCH_DATA_SUCCESS':
      return { ...state, loading: false, data: action.payload };
    case 'FETCH_DATA_FAILURE':
      return { ...state, loading: false, error: action.payload };
    default:
      return state;
  }
};

// Define the async action creator using Redux-Thunk
const fetchData = () => async (dispatch) => {
  dispatch({ type: 'FETCH_DATA_REQUEST' });

  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();

    dispatch({ type: 'FETCH_DATA_SUCCESS', payload: data });
  } catch (error) {
    dispatch({ type: 'FETCH_DATA_FAILURE', payload: error.message });
  }
};

// Create the store with Redux-Thunk middleware
const store = createStore(reducer, applyMiddleware(thunk));

// Dispatch the async action
store.dispatch(fetchData());
Copied!
Copied!
Copied!
Copied!

All versions