Chazzy97
Chazzy97

Reputation: 95

Problem with saving first element to array in todo

I have problem with my simple todo App in React with react-hooks.

When i get my inputValue and try to assign it to object and save in to my items Array, it doesn't work.

( The first assign after onSubmit action is empty array, and i completely don't know why. But the second button action work fine.

Can someone please help me out here?

https://codesandbox.io/s/young-sun-r2jdp?fontsize=14

Upvotes: 0

Views: 335

Answers (2)

Mark Shulhin
Mark Shulhin

Reputation: 119

You can do that sort of side effects(like console.log) in the useEffect hook, it will run after every items variable update and will log you the right thing

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

Upvotes: -1

Clarity
Clarity

Reputation: 10873

The problem is that you're doing console.log right after setting the new items, but React makes updates on new re-render, so you won't see the changes before the component re-renders.

To test, you can render the current items by adding this below your button element:

          <p>Got items:</p>
            {items.map((item, i) => (
              <div key={i}>{item.name}</div>
            ))}
          </div>

Upvotes: 3

Related Questions