I have the following code in which every time the user types a key, the useState variable index
shall be increased by 1. However, everytime it is run the variable does not update.
"use client";
import { useEffect, useState } from "react";
import Word from "./Word";
const PLACEHOLDER_STRING = "typing test website";
export default function Home() {
const [index, setIndex] = useState(0);
const splitWords = PLACEHOLDER_STRING.split("");
const wordsArray = splitWords.map((val, index) => {
return { word: val, index: index };
});
const [words, setWords] = useState(wordsArray);
useEffect(() => {
if (typeof window !== "undefined") {
window.addEventListener("keypress", keyPressed);
}
return () => {
if (typeof window !== "undefined") {
window.removeEventListener("keypress", keyPressed);
}
};
}, [])
const keyPressed = (e) => {
console.log(words);
const key = e?.key;
const changedWords = (words.map((val, i) => {
let val_ = val;
if(i == index) {
val_.wrote = key;
}
return val_;
}));
setWords(changedWords);
// HERE is where my problem occurs, every time I re click a key, it does not show it has increased by +1 from last key press.
setIndex(prev => prev + 1);
console.log(index);
};
return (
<div className="w-screen h-screen flex flex-col items-center pt-[4rem]">
<div className="w-[800px] h-[300px] border rounded-md p-[1rem] grid grid-cols-words">
{words.map((val) => (
<Word data={val} />
))}
</div>
</div>
);
}