React › State Management Libraries (Redux, Zustand & Recoil)
How do middleware, such as Redux Thunk, help handle asynchronous operations like API calls in Redux?
IntermediateAnswer
Regular Redux actions are plain objects and cannot directly contain asynchronous logic like a fetch call. Middleware like Redux Thunk lets you dispatch a function instead of a plain object, and that function can perform asynchronous work, like fetching data, before eventually dispatching the real action with the actual result.
function fetchUser(id) {
return async function (dispatch) {
dispatch({ type: 'FETCH_USER_START' });
const user = await fetch(`/api/users/${id}`).then((r) => r.json());
dispatch({ type: 'FETCH_USER_SUCCESS', payload: user });
};
}
store.dispatch(fetchUser(5));Real-world example A team fetches user profile data through a thunk action, which dispatches a loading action first, then dispatches a success action once the actual data arrives from the server, keeping their Redux store correctly updated throughout the process.