0

I have a react functional component. I have a state called current property.

const [currentProperty, setCurrentProperty] = useState({})

I am trying to assign an object using the setCurrentProperty but it is not working the stat is staying as a black object. Here is the current code:

  function handleEditingMortagePaymentOpen(id){
    setCurrentlyEditingMortgagePayments(true)
    setSelectedPropertyById(id)
    for(let i = 0; i < properties.length; i++){
      if(properties[i]['id'] == id){
        console.log(properties[i])
        setCurrentProperty(properties[i])
        console.log(currentProperty)
      }
    }
  }

This is what the console.log is showing

{id: 3, picture: '../images/unnamed.jpeg', price: 464000, status: 'Active', beds: 3, …}
address: "Plan 2 Plan, Neo at Mission Foothils"
agent: "John Doe"
baths: 3
beds: 3
broker: "JD Realty"
days_listed: 29
hoa: 12
home_insurance: 239
id: 3
living_space: 3964
mls: "OC3628342"
picture: "../images/unnamed.jpeg"
price: 464000
property_tax: 68
rent: 2200
sqft: 1939
status: "Active"
[[Prototype]]: Object
{}
  • you are expecting the console.log to reflect the change, but this is not how react state updates work. I would recommend you read up on how state updates are triggered in react – John Ruddell Oct 29 '21 at 05:27
  • Using a loop to continually set state isn't a great idea. – Andy Oct 29 '21 at 05:30
  • True, although this code is equivalent to a `arr.find(item); setCurrentProperty(item)` since its only matching by an id which I'd assume is a unique identifier. The issue is the set state behavior being async vs sync. Its a common question on SO. – John Ruddell Oct 29 '21 at 05:36

1 Answers1

1

This is the same issue mentioned in useState set method not reflecting change immediately

React setState or useState function will not instantly change your variable, it is an asynchronous process that will only set your value on its next render,

    console.log(properties[i])
    setCurrentProperty(properties[i])
    console.log(currentProperty)

This code show different logs as current property is not yet updated with the new one, To check the change of a state variable you can check it outside you function (before the return of component) or in a useEffect

 useEffect(()=> {
    conole.log(currentProperty) // this will console latest value on your every `currentProperty` update
 },[currentProperty])

or you can simply console it before you return the HTML, or inside HTML, value will automatically updates on its next render

Andy
  • 61,948
  • 13
  • 68
  • 95
sojin
  • 2,158
  • 1
  • 10
  • 18