Home > Blockchain >  How to fill a state with an array
How to fill a state with an array

Time:07-16

I'm trying to add a list inside a state using the set method, but my state remains empty

App.js

// Starts the screts word game
  const startGame = () => {
    // pick word and pick category
    const { word, category } = pickWordAndCategory();
    // create array of letters
    let wordLetters = word.split("");
    wordLetters = wordLetters.map((l) => l.toLowerCase());

    // Fill states
    setPickedCategory(category);
    setPickedWord(word);
    setLettersList(wordLetters);
    console.log('wordLetters', wordLetters);
    console.log('lettersList', lettersList);
    

    setGameState(stages[1].name);
  };

  const pickWordAndCategory = () => {
    // pick a random category
    const categories = Object.keys(words);
    const category = categories[Math.floor(Math.random() * Object.keys(categories).length)];
    console.log('category', category);

    // pick a random word
    const word = words[category][Math.floor(Math.random() * words[category].length)]
    console.log(word);

    return { word, category };
  }

Here is the browser log

When looking at the log we find our state empty

CodePudding user response:

States updates are asynchronous, so when you set a new state value and console.log() right after it, it's going to show the previous value, because the state hasn't been updated yet.

That's why your lettersList value show the old value of the state in the console (empty array).

CodePudding user response:

When you use setLettersList(...), you are not actually changing lettersList variable itself. Notice how when you declare it, const [lettersList, setLettersList] = useState([]); letterList is actually constant, so that variable can't even be changed. Instead, it tells React to rerun the function component, this time giving lettersList the new value. Therefore, for the updated value, it will only come once const [lettersList, setLettersList] = useState([]); is rerun again from the entire function being rerun again.

If you want to monitor changes to lettersList, you can do:

useEffect(() => {
  console.log(lettersList);
}, [lettersList]);

This will print lettersList every time it is updated.

  • Related