API Call Middleware
Show how to implement middleware that intercepts specific actions to perform API calls using fetch API, then dispatches a success or error action based on the response.
function apiCallMiddleware({ dispatch }) {
return function(next) {
return function(action) {
// Check if the action should trigger an API call
if (action.type === 'API_CALL_REQUEST') {
// Perform the actual API call
fetch(action.payload.url)
.then(response => response.json())
.then(data => {
// Dispatch a success action with the data
dispatch({ type: 'API_CALL_SUCCESS', payload: data });
})
.catch(error => {
// Dispatch an error action in case the API call fails
dispatch({ type: 'API_CALL_FAILURE', payload: error.toString() });
});
}
// Proceed with the action regardless of whether it triggered an API call or not
return next(action);
};
};
}
This middleware intercepts actions to check if they require an API call as indicated by their type ('API_CALL_REQUEST'). If so, it performs the call using the fetch API, then dispatches either a success or error action based on the response. This allows asynchronous operations to be initiated from action dispatches while keeping the action creators and reducers pure and synchronous.