Redux middleware manages asynchronous actions by intercepting them prior to reaching the reducer. This enables the execution of async logic, such as API calls, and depending on the outcome, it dispatches standard synchronous actions to modify the state.
With redux-thunk: Action creators return a function instead of an action object. This function performs the async operation and manually dispatches actions.
Example:
export const fetchUser = (userId) => {
return async (dispatch) => {
dispatch({ type: 'FETCH_USER_START' });
try {
const response = await fetch(`/api/users/${userId}`);
const data = await response.json();
dispatch({ type: 'FETCH_USER_SUCCESS', payload: data });
} catch (error) {
dispatch({ type: 'FETCH_USER_ERROR', error });
}
};
};