To implement action creators in Redux for async actions, use Redux Thunk middleware, which allows action creators to return functions (instead of plain objects).
Steps:
Install Redux Thunk:
npm install redux-thunk
Apply Middleware:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
const store = createStore(rootReducer, applyMiddleware(thunk));
Async Action Creator Example:
const fetchData = () => {
return async (dispatch) => {
dispatch({ type: 'FETCH_START' });
try {
const res = await fetch('/api/data');
const data = await res.json();
dispatch({ type: 'FETCH_SUCCESS', payload: data });
} catch (error) {
dispatch({ type: 'FETCH_ERROR', error });
}
};
};