0

I have this problem. I try to update mi object with useState but doesn't work. Below i paste the real case. I use React 18.2.0

 const [filter, setFilter] = useState({year: 0, month: 0});


 const buttonClick = (data) => {

  // Jenuary 1st 2022
  let datObj = {
     year: 2022,
     month: 1
  }
  setFilter((obj) => { return {...obj, ...{year: datObj.year, month: datObj.month} }});
  console.log(filter);
  // 
  // print always {year: 0, month: 0}

I Try many many times...but i suppose I'm wrong...or i don't understand..Can you help me? Thanks.

Bonci Marco
  • 301
  • 2
  • 5
  • 17
  • 1
    `setFilter` does not update `filter` immediately, but you are logging it immediately after. React batches state updates. If you want to get the latest value of `filter`, create a `useEffect` with filter being in the dependency array. – Terry Oct 27 '22 at 12:28
  • print the log in component function body outside of event handler .... – KcH Oct 27 '22 at 12:31
  • @Terry I'm try to call console.log(filter) in the another function but filter is not updated. Why? – Bonci Marco Oct 27 '22 at 12:31
  • Because the console logging is not triggered by changes to filter. You need to show us more code and context. Where are you expected to use the updated value of filter? – Terry Oct 27 '22 at 12:32
  • I try to use filter into another button. I have a table and i click on row action i try to read filter. – Bonci Marco Oct 27 '22 at 12:56

1 Answers1

1

UseState hook is asynchronous, and because of that it will take some time time to update the value, so if you need to check the value change you will have to use useEffect and add a filter as a dependency for that useEffect, and console log the value in that useEffect.

shamal iroshan
  • 189
  • 1
  • 3
  • 7
  • 1
    This question has been asked so many times on StackOverflow already: vote to close it as duplicate instead. – Terry Oct 27 '22 at 12:38