To write an action creator that handles errors in an asynchronous API call, follow these steps in a Redux-based setup:
Create the Action Types: Define action types for both success and error cases.
Write the Async Action Creator: Use async/await to handle the API call. Catch any errors and dispatch the error action.
Here’s an example using Redux Thunk for asynchronous actions:
// Action Types
const FETCH_DATA_REQUEST = 'FETCH_DATA_REQUEST';
const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
const FETCH_DATA_FAILURE = 'FETCH_DATA_FAILURE';
// Action Creator for Async API call
export const fetchData = () => async (dispatch) => {
dispatch({ type: FETCH_DATA_REQUEST });
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
if (response.ok) {
dispatch({ type: FETCH_DATA_SUCCESS, payload: data });
} else {
throw new Error(data.message || 'Failed to fetch data');
}
} catch (error) {
dispatch({ type: FETCH_DATA_FAILURE, error: error.message });
}
};