0

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>
  );
}

  • 2
    `console.log(index)` just after `setIndex(prev => prev + 1);` makes 0 sense due to 1) `setIndex` does not modify `index` immediately, it will be updated on next render only and 2) you are attaching function `keyPressed` once the component is mounted, and you are using closure-captured variables in it, their values are basically frozen in time at the moment you attached the function as a listener (until they are mutated directly, i.e. array.push or composite object changes). – Sergey Sosunov Apr 15 '23 at 18:08
  • 1
    Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Konrad Apr 15 '23 at 18:12

0 Answers0