In this post we will create a custom redux middleware.
A redux middleware listens for actions, and choose either to ignore it and let redux handle it, or handle the action by itself.
Let review the steps for using a custom redux middleware. First, add our middleware to the store default middlewares:
import {configureStore, getDefaultMiddleware} from '@reduxjs/toolkit'
import counterReducer from '../features/counter/counterSlice'
export default configureStore({
reducer: {
counter: counterReducer,
},
middleware: [
...getDefaultMiddleware(),
refreshMiddleware,
],
})
Next, activate our middleware only for a specific type of action:
function refreshMiddleware({dispatch, getState}) {
return next => action => {
if (action.type === 'refresh') {
handleAction(action, dispatch, getState)
} else {
return next(action)
}
}
}
And lastly, we want to handle our action.
In this case we will send an async request, and update redux with its result using a new type of action.
function handleAction(action, dispatch, getState) {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
const state = getState()
dispatch({
type: 'set-user',
payload: {
counter: state.counter.value,
userId: json.userId,
},
})
},
)
}
Final Note
While easy to perform, custom middleware is poorly documented in the redux documentation. I hope this short post would assist you to implement your own middlware.
That's said, make sure to use redux middleware only as a last resort, a prefer using existing mechanisms such as simple reducers, and redux-thunk.
No comments:
Post a Comment