reactjs – React JS – array state variable not behaving properly
I have an array state variable in a file App.jsx.
const [taken, setTaken] = useState([]);
The only place in the app where this gets updated looks like this:
if (!taken.includes(letterPos)) {
setTaken((prev) => [...prev, letterPos]);
}
As you can see, it should only add letterPos to the array if it’s not already in there; the array should never contain duplicates.
When the user hits Enter, I want to clear the array. But when I run this code:
const onEnter = () => {
setTaken((previousState) => []);
console.log(taken);
}
I get
I have also tried
const onEnter = () => {
//reset array of taken letter positions
useEffect(() => {
setTaken([]);
}, [taken]);
}
But then I get an error that Hooks can only be called inside of the body of a function component.
Read more here: Source link

