To manage async API calls in a React app using redux-thunk:
Install Middleware:
npm install redux-thunk
Configure Store:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const store = createStore(rootReducer, applyMiddleware(thunk));
Create Async Action Creator:
export const fetchData = () => async (dispatch) => {
dispatch({ type: 'FETCH_REQUEST' });
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
dispatch({ type: 'FETCH_SUCCESS', payload: data });
} catch (error) {
dispatch({ type: 'FETCH_FAILURE', payload: error });
}
};
Dispatch in Component:
import { useDispatch } from 'react-redux';
import { useEffect } from 'react';
import { fetchData } from './actions';
const MyComponent = () => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchData());
}, [dispatch]);
return <div>...</div>;
};