Enhancing Redux Thunks with Action Types
Provide an example of a Redux thunk that uses action types to dispatch actions rather than relying on AnyAction.
// Define action types
const FETCH_DATA_BEGIN = 'FETCH_DATA_BEGIN';
const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
const FETCH_DATA_FAILURE = 'FETCH_DATA_FAILURE';
Define the action types to represent the states of the asynchronous operation.
// Action creators for each state of the asynchronous operation
const fetchDataBegin = () => ({
type: FETCH_DATA_BEGIN
});
const fetchDataSuccess = data => ({
type: FETCH_DATA_SUCCESS,
payload: { data }
});
const fetchDataFailure = error => ({
type: FETCH_DATA_FAILURE,
payload: { error }
});
Create action creators that return the appropriate action object for each action type.
// A Redux thunk that uses the defined action types
const fetchData = url => {
return dispatch => {
dispatch(fetchDataBegin());
return fetch(url)
.then(handleErrors)
.then(res => res.json())
.then(json => {
dispatch(fetchDataSuccess(json));
return json;
})
.catch(error => dispatch(fetchDataFailure(error)));
};
};
Implement the Redux thunk that dispatches the `fetchDataBegin` action before making the fetch request, and based on the result, it either dispatches `fetchDataSuccess` or `fetchDataFailure`.
// Function to handle HTTP errors
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
Include a helper function to handle potential HTTP errors in the request.