I don't understand why in setProjectIndex inside SwitchProject function not updating my projectIndex state :
const WorkPreview = ({project, projects}) => {
const [currProject, setCurrProject] = useState(projects[0]);
const [projectIndex, setProjectIndex] = useState(0);
useEffect(() => {
console.log("useEffect idx", projectIndex) // log: 1 when onClick to Right Button
}, [projectIndex])
const SwitchProject = (incrDecrAmount) => {
let nextIndex = projectIndex + incrDecrAmount;
if (nextIndex >= 0 && nextIndex < (projects.length-1)) {
setProjectIndex(projectIndex + incrDecrAmount); // sets 0
console.log("projectIndex", projectIndex) // log: 0 when onClick to Right Button (increment by 1)
console.log("nextIdx", nextIndex) // log: 1 when onClick to Right Button
setCurrProject(projects[projectIndex]);
console.log("", projects[projectIndex]); // gives projects[0] not projects[1]
}
}
return (
<div className="works__preview" id="workPreview">
<button className="works__itemBtn" id="btnfixedLeft" onClick={() => { SwitchProject(-1) }}>
<Icon.ArrowLeft></Icon.ArrowLeft>
</button>
<button className="works__itemBtn" id="btnfixedRight" onClick={() => { SwitchProject(1) }}>
<Icon.ArrowRight></Icon.ArrowRight>
</button>
</div>
)
I've checked other questions and try different ways but gives the same result
Can someone explain me that and gives me the solution ?