Redux with Thunk and Fetching

Goal: After completing this material, you will be able to:

What is Middleware in Redux?

Think of Redux as a delivery service between a restaurant (your component) and the customer (the store). Middleware is like a quality control checkpoint — it inspects, modifies, or even halts the packages (actions) before they reach their destination.

Middleware allows you to:

Attaching Middleware: Redux Thunk and Logger


// Store setup with Redux Thunk and Logger
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import logger from 'redux-logger';
import rootReducer from './reducers';

const store = createStore(
  rootReducer,
  applyMiddleware(thunk, logger)
);
  

Explanation: We apply two middlewares here:

What is Redux Thunk?

Imagine Redux Thunk as a translator that allows action creators to speak async language. Normally, action creators return plain objects. With Thunk, they can return functions that delay execution and handle async operations like fetching data.

When to Use Thunk?

Real-World Example: Ordering food online — you send a request (fetch), wait for the food (response), then update the UI (dispatch new action).

Making a Fetch Request to an API


fetch('https://api.example.com/items')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));
  

Explanation: We request data, wait for it to arrive (asynchronously), then process it.

Thunk Action Creator Example


const fetchItems = () => {
  return dispatch => {
    dispatch({ type: 'ITEMS_LOADING' });

    fetch('https://api.example.com/items')
      .then(response => response.json())
      .then(data => {
        dispatch({ type: 'ITEMS_SUCCESS', payload: data });
      })
      .catch(error => {
        dispatch({ type: 'ITEMS_ERROR', error });
      });
  };
};
  

Explanation:

Refactor Async Call from Component to Redux

Before Thunk (inside component):


useEffect(() => {
  fetch('https://api.example.com/items')
    .then(response => response.json())
    .then(data => setItems(data));
}, []);
  

After Thunk (Redux handles async):


useEffect(() => {
  dispatch(fetchItems());
}, [dispatch]);
  

Advantages of Thunk + Redux

Analogy Recap

Extra Learning Resources

Further Related Topics