Why is reducer not updating states in React?!
The problem:
Updating the state with useReducer doesn't update state. Look at the code below:
const quizReducer = async (state, action) => {
switch (action.type) {
case POPULATE:
return { ...state, questions: action.payload, ready: true };
}
};
const [{ questions, ready }, dispatch] = useReducer(quizReducer, intialState);
useEffect(() => {
if (controller.current !== null) return console.log("Hello");
controller.current = new AbortController();
fetch(`http://localhost:3000/api/v1/bootcamps`)
.then((res) => res.json())
.then((result) => {
const data = result.data;
dispatch({ type: POPULATE, payload: data });
})
.catch((error) => {
console.error(error);
});
}, []);
Spot the problem? Here is what I tried to do:
- Initially I thought it's the problem of the API itself, so I tried logging the data. But to no avail.
- I thought useEffect running twice has to do with it not being able to return the data properly, but nope.
But the solution is to simply declare the reducer is synchronous, instead of asynchronous.
So just remove the 'async' from the 'quizReducer' like this:
const quizReducer = async (state, action) => {
switch (action.type) {
case POPULATE:
return { ...state, questions: action.payload, ready: true };
}
};
const [{ questions, ready }, dispatch] = useReducer(quizReducer, intialState);
useEffect(() => {
if (controller.current !== null) return console.log("Hello");
controller.current = new AbortController();
fetch(`http://localhost:3000/api/v1/bootcamps`)
.then((res) => res.json())
.then((result) => {
const data = result.data;
dispatch({ type: POPULATE, payload: data });
})
.catch((error) => {
console.error(error);
});
}, []);
Comments
Post a Comment