2

Learning React, making a very simple to-do list. I am able to add items as expected. When I input something and click "add", the item shows up on the page. But I noticed that if I try to console.log the result, the array that gets consoled is always missing the last item. Eg. If I enter "bread" and click "add", it will show on the page, but in the console, I just get an empty array. If I then enter "milk" and click "add", on the page both bread and milk show up but in the console, I only see ["bread"] as the array. Why is this happening?

import { useRef, useState } from "react";

export default function App() {
  const [items, setItems] = useState([]);
  const inputRef = useRef();

  function onSubmit(e) {
    e.preventDefault();
    const value = inputRef.current.value;
    setItems(prev => [...prev, value]);
    console.log(items);
    inputRef.current.value = "";
  }

  return (
    <main>
      <form onSubmit={onSubmit}>
        <input type="text" ref={inputRef} />
        <button type="submit">Add</button>
      </form>
      <h3>My List:</h3>
      <ul>
        {items.map(item => (
          <li>{item}</li>
        ))}
      </ul>
    </main>
  );
}
AlwaysLearning
  • 311
  • 4
  • 12

3 Answers3

2

Here the setItems is not asynchronous. Which mean. In the next line you will not get the updated value. Or other words it doesn't wait for updating the value then go to the next line.

So what is happening here is. If you console.log after thesetItems it will give you old state. Log it outside the function anywhere. Usually I keep all my logs before return statement

console.log(items)
return (
.........
)

Official doc

moshfiqrony
  • 4,303
  • 2
  • 20
  • 29
0

Basically https://reactjs.org/docs/react-component.html#setstate

And I would consider this topic a duplicate of any of the many

Why does calling react setState method not mutate the state immediately?

React setState not updating state

Breezer
  • 10,410
  • 6
  • 29
  • 50
0

Yesterday I answered a question, which is similar in nature to your question.

So you can refer: Related to weird behaviour of react useState and useEffect

flosisa
  • 189
  • 7