I am trying to create a state which will keep track of a list by the states value. It increases or decreases by 1. However, it does not work exactly how I am expecting it to. I am using the up and down arrow keys to increment or decrement the value, and whenever I "change direction" it updates the state once more in the previous direction before it goes the correct way. I provide an image with console logs to make it clear what I mean.
I will also provide some code of course.
export const SearchBar = (props) => {
...
const [currentItem, setCurrentItem] = useState(0);
...
...
const handleKeyPress = (e) => {
const keyPressed = e.key;
if (keyPressed === "ArrowDown") {
setCurrentItem(currentItem +1);
} else if (keyPressed === "ArrowUp" && currentItem >= 0) {
setCurrentItem(currentItem -1);
} else if (keyPressed === "Enter") {
dispatch(setSearchTerm(''));
setCurrentItem(0);
}
}
}