Error Handling in Redux Thunk 3.0
Show how to implement robust error handling in Redux Thunk 3.0 by using try-catch blocks and dispatching error action types to the Redux store.
// Define action types
const FETCH_DATA_REQUEST = 'FETCH_DATA_REQUEST';
const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
const FETCH_DATA_FAILURE = 'FETCH_DATA_FAILURE';
// Action creators for each scenario
const fetchDataRequest = () => ({ type: FETCH_DATA_REQUEST });
const fetchDataSuccess = (payload) => ({ type: FETCH_DATA_SUCCESS, payload });
const fetchDataFailure = (error) => ({ type: FETCH_DATA_FAILURE, error });
// Thunk action creator
const fetchData = () => {
return async (dispatch) => {
dispatch(fetchDataRequest());
try {
const response = await fetch('https://example.com/data');
const data = await response.json();
dispatch(fetchDataSuccess(data));
} catch (error) {
dispatch(fetchDataFailure(error));
}
};
};
This example includes action type definitions, action creators, and a thunk action creator which uses async/await with try-catch blocks for fetching data asynchronously and handling errors. The `fetchData` thunk dispatches request, success, and failure actions based on the outcome of the fetch call. If an error occurs during the fetch or data processing, it dispatches a failure action with the caught error.