I am working on a react project and have an issue with the using current correct state value. I've recreated the issue in a small dummy project that contains a Parent component and a Child Component. The Child is passed down props from the Parent component, one state variable and one function that updates said state utilizing react hooks (useState). Within the original function residing in the Parent component is a call to a second function that performs an action based on the current state. I have the console logs and result showing that the passed down function sends back up the correct value to update, but the following function does not use the updated value, instead seems to always be one render behind.
I've attempted using async/await as well as the useEffect hook. I've been able to get the "expected" result using some variation of useEffect in this small dummy project however it didn't translate into the actual project duo to their being more function calls that also depend on a state value, although I may just be misunderstanding/ doing something wrong.
export const Parent = () => {
const [count, setCount] = useState(0);
const [fruit, setFruit] = useState(null);
const counter = (index) => {
console.log("index passed in: ", index);
setCount(index);
secondMethod()
}
const secondMethod = () => {
console.log('state of count in second method', count);
const arr = ['apple', 'cherry', 'orange', 'kiwi', 'berry'];
setFruit(arr[count]);
}
return (
<div>
<p>Hello from Parent, current count: {count}</p>
<Child counter={counter} count={count}/>
<p>result of second method: {fruit}</p>
</div>
);
}
export const Child = ({ counter, count }) => {
return (
<div>
<p>Child comp</p>
<button onClick={() => counter(count + 1)}>
Click on send counter
</button>
</div>
);
}
The console log value on index is correct as well as the { count } output. The result of the console log from the secondMethod and therefore the state of the setFruit is incorrect and uses the state from one render behind? So count will be displayed as 1 but the secondMethod will still have count as value 0 so displays "apple" instead of "cherry". I appreciate any and all help/suggestions, thanks!