I cannot figure out why the state isn't changing with this reducer function setup in React. I just want to console log the new state from the reducer function?
const [lessonState, dispatchLesson] = useReducer(lessonReducer, {
lesson: 0,
isComplete: false,
});
const lessonReducer = (state, action) => {
if (action.type === "UPDATE") {
return { lesson: action.lesson, isComplete: true };
}
};
const initializeLesson = () => {
dispatchLesson({ type: "UPDATE", lesson: 2 });
console.log(lessonState);<------
};
//other stuff//
export default function Dashboard() {
useEffect(() => {
context.initializeCourse();
}, []);
return (
<Fragment>
<div className="dashboard">
<h1>Hello</h1>
</div>
</Fragment>
);
}
CodePudding user response:
You can not get updated reducer state after dispatching it immediately. To get the update state data you can do following:
useEffect(() => {
console.log("lessonState", lessonState);
}, [lessonState]);
So when state is updated, this useEffect will be triggered and you will get your updated state.