Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

i'm learning React and React hooks and i have a question. I have this state called rooms that contains array of room objects. I created a component that adds a new room. You fill out a form and when a submit button is clicked it fires up a function where I edited the state with setRooms([...rooms, newRoom]) and while it updates the rooms on the page. For some reason when I try to log it in the console (in the same onSubmit function that edited rooms the first time), it shows the previous state, even though it's supposed to be updated and i can tell it's updated, because the new room is displayed on the page.

Please help me understand this, i can't wrap my head around it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
247 views
Welcome To Ask or Share your Answers For Others

1 Answer

That's surely because the rooms state hasn't been updated yet when you console.log it.

You should keep in mind that useState is assyncronus, meaning that it's altered value it's not instantly reflected.

If you do:

const handleSubmit = (newRoom) => {
  setRooms([...rooms, newRoom])
  console.log(rooms)
  // Possibly won't get the desired result
}

But as React, when a state is changed, it rerenders. You can put the console.log anywhere before the return (o render function if it's a class)

const Component = () => {
  const handleSubmit = (newRoom) => {
    setRooms([...rooms, newRoom])
  }

  console.log(rooms)
    // Possibly you will get the desired result

  return (
     ..your component JSX
  )
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...