To manage asynchronous actions (e.g., API calls), you typically use middleware like redux-thunk or redux-saga. Here's how to update state based on async action outcomes:
Dispatch Async Actions: Use middleware to dispatch actions that perform async operations (e.g., API calls).
Handle Action Outcomes in Reducers: Reducers listen for specific action types (e.g., FETCH_SUCCESS, FETCH_FAILURE) to update the state based on the async operation's outcome.
Example:
1. Define Action Types:
const FETCH_REQUEST = 'FETCH_REQUEST';
const FETCH_SUCCESS = 'FETCH_SUCCESS';
const FETCH_FAILURE = 'FETCH_FAILURE';
2. Create Async Action (using redux-thunk):
const fetchData = () => async (dispatch) => {
dispatch({ type: FETCH_REQUEST });
try {
const response = await apiCall();
dispatch({ type: FETCH_SUCCESS, payload: response.data });
} catch (error) {
dispatch({ type: FETCH_FAILURE, payload: error.message });
}
};
3. Reducer to Handle Async Outcomes:
const initialState = {
loading: false,
data: null,
error: null,
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case FETCH_REQUEST:
return { ...state, loading: true, error: null };
case FETCH_SUCCESS:
return { ...state, loading: false, data: action.payload };
case FETCH_FAILURE:
return { ...state, loading: false, error: action.payload };
default:
return state;
}
};