In my code, I have a provider component. In this component, I have state objects and some functions that change state. The problem is I want to change state depending on state value but in my functions, state stays the same as it was initialized.
Part of my code:
const AppContextProvider = () => {
const [historyState, setHistoryState] = useState({
historyLength: 0,
currHistoryIdx: 0,
});
const historyAdd = () => {
if (historyState.currHistoryIdx < historyState.historyLength)
setHistoryState((state) => ({
historyLength: state.currHistoryIdx + 1,
currHistoryIdx: state.currHistoryIdx + 1,
}));
else
setHistoryState((state) => ({
historyLength: state.historyLength + 1,
currHistoryIdx: state.historyLength + 1,
}));
};
return (
<AppContext.Provider
value={{ state, centerState, rpState, historyState, functions }}
>
<App />
</AppContext.Provider>
);
};
I need to check the state to make a decision on how to change it, but in this function, the state always stays the same as it was initialized and because of this, my condition doesn't work properly.
I can get actual state only inside the setHistoryState
function using the state
parameter, but this solution doesn't suit me because I have more complex functions. Also if you use useEffect
to check if the state changed, it will show the actual state in console.
What am I doing wrong and how can I fix it?