Blog>
Snippets

Typed Middleware for API calls

Create a typed middleware example for making API calls and dispatching actions based on API responses, ensuring correct types for request params and response data.
// Define action types
const API_CALL_REQUEST = 'API_CALL_REQUEST';
const API_CALL_SUCCESS = 'API_CALL_SUCCESS';
const API_CALL_FAILURE = 'API_CALL_FAILURE';

// Define action creators with types for request parameters and response
function apiCallRequest(params) {
  return { type: API_CALL_REQUEST, payload: params };
}

function apiCallSuccess(responseData) {
  return { type: API_CALL_SUCCESS, payload: responseData };
}

function apiCallFailure(error) {
  return { type: API_CALL_FAILURE, payload: error };
}

// Typed middleware for API calls
const apiMiddleware = ({ dispatch }) => (next) => async (action) => {
  next(action);
  if (action.type === API_CALL_REQUEST) {
    try {
      // Make the API call with typed request parameters
      const response = await fetch('/api/resource', {
        method: 'POST',
        body: JSON.stringify(action.payload),
        headers: {
          'Content-Type': 'application/json'
        }
      });
      const data = await response.json();
      // Dispatch success action with typed response data
      dispatch(apiCallSuccess(data));
    } catch (error) {
      // Dispatch failure action in case of an error
      dispatch(apiCallFailure(error.toString()));
    }
  }
};
This piece of code defines typed actions and a middleware to handle API calls. It specifies the types for the request parameters and response data. The middleware intercepts API call actions, performs the fetch request, and dispatches success or failure actions based on the API response.