Blog>
Snippets

Creating a middleware for API calls

Showcase a middleware that handles API calls by intercepting specific action types to perform HTTP requests.
const apiMiddleware = store => next => action => {
  if (!action.meta || action.meta.type !== 'api') {
    return next(action);
  }

  const { url, method, data, onSuccess, onFailure } = action.meta;

  fetch(url, {
    method,
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(data)
  })
  .then(response => response.json())
  .then(data => store.dispatch({ type: onSuccess, payload: data }))
  .catch(error => store.dispatch({ type: onFailure, payload: error }));
};
This middleware function intercepts actions with a meta property of type 'api', and performs an HTTP request based on the action's metadata. It dispatches a new action on success or failure.
// Usage example dispatched from a component or other part of the application
store.dispatch({
  type: 'API_CALL',
  meta: {
    type: 'api',
    url: 'https://api.example.com/data',
    method: 'GET',
    onSuccess: 'API_CALL_SUCCESS',
    onFailure: 'API_CALL_FAILURE'
  }
});
This is an example of how an action is dispatched that the middleware would intercept and handle. The action contains metadata for URL, method, and action types for success or failure responses.