Can useReducer be used with an asynchronous action?
useReducer
itself doesn’t directly handle asynchronous logic, but you can combine it with useEffect
or an external async function.
function reducer(state, action) {
switch (action.type) {
case "fetch_start":
return { ...state, loading: true };
case "fetch_success":
return { ...state, loading: false, data: action.payload };
case "fetch_error":
return { ...state, loading: false, error: action.error };
default:
return state;
}
}
function Component() {
const [state, dispatch] = useReducer(reducer, { loading: false, data: null, error: null });
useEffect(() => {
dispatch({ type: "fetch_start" });
fetch("https://api.example.com/data")
.then((res) => res.json())
.then((data) => dispatch({ type: "fetch_success", payload: data }))
.catch((error) => dispatch({ type: "fetch_error", error }));
}, []);
return state.loading ? <p>Loading...</p> : <p>Data: {JSON.stringify(state.data)}</p>;
}