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 …


This content originally appeared on DEV Community and was authored by Randy Rivera

  • 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)
);
  • 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);
  }
};

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


This content originally appeared on DEV Community and was authored by Randy Rivera


Print Share Comment Cite Upload Translate Updates
APA

Randy Rivera | Sciencx (2021-11-30T18:55:00+00:00) Use Middleware to Handle Asynchronous Actions. Retrieved from https://www.scien.cx/2021/11/30/use-middleware-to-handle-asynchronous-actions/

MLA
" » Use Middleware to Handle Asynchronous Actions." Randy Rivera | Sciencx - Tuesday November 30, 2021, https://www.scien.cx/2021/11/30/use-middleware-to-handle-asynchronous-actions/
HARVARD
Randy Rivera | Sciencx Tuesday November 30, 2021 » Use Middleware to Handle Asynchronous Actions., viewed ,<https://www.scien.cx/2021/11/30/use-middleware-to-handle-asynchronous-actions/>
VANCOUVER
Randy Rivera | Sciencx - » Use Middleware to Handle Asynchronous Actions. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/11/30/use-middleware-to-handle-asynchronous-actions/
CHICAGO
" » Use Middleware to Handle Asynchronous Actions." Randy Rivera | Sciencx - Accessed . https://www.scien.cx/2021/11/30/use-middleware-to-handle-asynchronous-actions/
IEEE
" » Use Middleware to Handle Asynchronous Actions." Randy Rivera | Sciencx [Online]. Available: https://www.scien.cx/2021/11/30/use-middleware-to-handle-asynchronous-actions/. [Accessed: ]
rf:citation
» Use Middleware to Handle Asynchronous Actions | Randy Rivera | Sciencx | https://www.scien.cx/2021/11/30/use-middleware-to-handle-asynchronous-actions/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.