I have a state variable that should be updated when the condition is met, but whenever it makes it inside the if
statement the index
is always 0.
import React, { useState, useEffect } from 'react';
import { words } from "./words.json";
import TypingTest from './components/TypingTest';
import './App.css';
function App() {
const [index, setIndex] = useState(0);
const onKeyPress = (event) => {
console.log("Current key: ", event.key);
switch (event.key) {
default:
if(event.key === words[index]){
setIndex((index) => index + 1);
console.log("New index: ", index);
}else{
console.log('Wrong' , words[index]);
}
break;
}
};
useEffect(() => {
document.addEventListener('keydown', onKeyPress);
return () => {
document.removeEventListener('keydown', onKeyPress);
};
}, [])
return (
<div className="App">
<header className="App-header">
<TypingTest words={words} index={index}/>
</header>
</div>
);
}
export default App;
Here is console output
Current key: L
New index: 0
Current key: L
New index: 0
Current key: L
New index: 0
Current key: L
New index: 0
Current key: L
New index: 0