Skip to content

Instantly share code, notes, and snippets.

@uladzislau-stuk
Created May 26, 2019 13:30
Show Gist options
  • Save uladzislau-stuk/02cd788b79f1ea328d172f569afc72e4 to your computer and use it in GitHub Desktop.
Save uladzislau-stuk/02cd788b79f1ea328d172f569afc72e4 to your computer and use it in GitHub Desktop.
[Redux Middleware] #redux

Redux provides middleware designed specifically for asynchronous purposes, called Redux Thunk middleware.

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. 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.

In this example, an asynchronous request is simulated with a setTimeout() call. It's common to dispatch 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. This is what you'll use to dispatch your actions, you simply pass the action directly to dispatch and the middleware takes care of the rest.

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
dispatch(requestingData())
setTimeout(function() {
let data = {
users: ['Jeff', 'William', 'Alice']
}
// dispatch received data action here
dispatch(receivedData(data))
}, 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(
// reducer
asyncDataReducer,
// middleware
Redux.applyMiddleware(ReduxThunk.default)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment