DEV Community

Randy Rivera
Randy Rivera

Posted on

Use Middleware to Handle Asynchronous Actions

  • At some point you'll need to call asynchronous endpoints in your Redux app, so how do you handle these types of requests? Redux provides middleware designed specifically for this purpose, called Redux Thunk middleware.
  • I'm still kinda effy about this particular topic so like you I myself am still learning.
  • To include Redux Thunk middleware, you pass it as an argument to Redux.applyMiddleware(). This statement is then provided as a second optional parameter to the createStore() function. The code will be provided below. Take a look at the code at the bottom of the editor to see this. Then, to create an asynchronous action, you return a function in the action creator that takes dispatch as an argument. Within this function, you can dispatch actions and perform asynchronous requests.

  • Code:

const REQUESTING_DATA = 'REQUESTING_DATA'
const RECEIVED_DATA = 'RECEIVED_DATA'

const requestingData = () => { return {type: REQUESTING_DATA} }
const receivedData = (data) => { return {type: RECEIVED_DATA, users: data.users} }

const handleAsync = () => {
  return function(dispatch) {
    // Dispatch request action here

    setTimeout(function() {
      let data = {
        users: ['Jeff', 'William', 'Alice']
      }
      // Dispatch received data action here

    }, 2500);
  }
};

const defaultState = {
  fetching: false,
  users: []
};

const asyncDataReducer = (state = defaultState, action) => {
  switch(action.type) {
    case REQUESTING_DATA:
      return {
        fetching: true,
        users: []
      }
    case RECEIVED_DATA:
      return {
        fetching: false,
        users: action.users
      }
    default:
      return state;
  }
};

const store = Redux.createStore(
  asyncDataReducer,
  Redux.applyMiddleware(ReduxThunk.default)
);
Enter fullscreen mode Exit fullscreen mode
  • Here an asynchronous request is simulated with a setTimeout() call. Dispatching an action before initiating any asynchronous behavior so that your application state knows that some data is being requested (this state could display a loading icon, for instance). Then, once you receive the data, you dispatch another action which carries the data as a payload along with information that the action is completed.
  • Remember that you're passing dispatch as a parameter to this special action creator.
  • We need to write both dispatches in the handleAsync() action creator. Dispatch requestingData() before the setTimeout(). Then, after you receive the data, dispatch the receivedData()action, passing in this data.
  • Treat the dispatch argument as a function and pass the action events in it.

  • Answer:

const handleAsync = () => {
  return function(dispatch) {
    dispatch(requestingData())
    setTimeout(function() {
      let data = {
        users: ['Jeff', 'William', 'Alice']
      }
      dispatch(receivedData(data)) // This sequence mimics the process of requesting the data, receiving the data and then dispatching the received data.

    }, 2500);
  }
};
Enter fullscreen mode Exit fullscreen mode

Larson, Q., 2019. Frontend Development Libraries. [online] Freecodecamp.org. Available at: https://www.freecodecamp.org/learn/front-end-development-libraries/redux

Top comments (0)