Home > Blockchain >  In React, why is the last array item missing in console.log?
In React, why is the last array item missing in console.log?

Time:10-30

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

setItems() is asynchronous, which means that at the time you console.log the state, it's not updated yet

Solution 1:use useEffect() hook

useEffect(() => {
    // action on update of items
}, [items]);

Solution 2:use simple variable instead of usestate()

const items = [];

To know more about problem solution go here

  • Related