To create an action creator that dispatches multiple actions during an async operation (e.g., using Redux Thunk), follow these steps:
Install Redux Thunk: Ensure you have redux-thunk middleware set up in your Redux store.
Define Action Types: Create action types for different stages of the async operation (e.g., start, success, failure).
Create Action Creators: Write action creators for each stage.
Write the Async Action Creator: Use redux-thunk to dispatch multiple actions during the async operation.
Here’s an example:
import axios from 'axios';
// Step 2: Define Action Types
const FETCH_DATA_START = 'FETCH_DATA_START';
const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
const FETCH_DATA_FAILURE = 'FETCH_DATA_FAILURE';
// Step 3: Create Action Creators
const fetchDataStart = () => ({
type: FETCH_DATA_START,
});
const fetchDataSuccess = (data) => ({
type: FETCH_DATA_SUCCESS,
payload: data,
});
const fetchDataFailure = (error) => ({
type: FETCH_DATA_FAILURE,
payload: error,
});
// Step 4: Write the Async Action Creator
const fetchData = () => {
return async (dispatch) => {
dispatch(fetchDataStart()); // Dispatch start action
try {
const response = await axios.get('https://api.example.com/data'); // Async operation
dispatch(fetchDataSuccess(response.data)); // Dispatch success action
} catch (error) {
dispatch(fetchDataFailure(error.message)); // Dispatch failure action
}
};
};
export default fetchData;