Simeon Nakov
Simeon Nakov

Reputation: 1048

React accessing a property of an object returns old data, when object has been updated

I have an object in my component props which I'll call data. This object is updated dynamically. However a problem arises when I try to get a property of the data object, it returns the old data from the object, even though the object is updated.

For example console.log(data) returns

{
    items: [{name: "NEW NAME"}]
}

But that's not the case when I try to access the property directly, because console.log(data.items[0].name) returns "OLD NAME". I'm pretty sure the component updates since the object contains the new data. The problem is that it renders the older name.

Another details is that it returns what the previous name was, so for example if I pass new data console.log(data) returns

{
    items: [{name: "EVEN NEWER NAME"}]
}

while console.log(data.items[0].name) would return "NEW NAME".

I'll gladly provide more info if needed.

Upvotes: 0

Views: 144

Answers (1)

prasanth
prasanth

Reputation: 61

Objects are evaluated each time it's value is changed in browser's dev tools. So even if the the object was {name: "OLD NAME"} when the console.log runs, it's value gets updated later and displays {name: "NEW NAME"}

But when you console data.items[0].name it's returning a string "OLD NAME" and it won't get evaluated automatically in Dev tools later. I would suggest rendering it on the page instead of using console to check if it's getting updated correctly

Upvotes: 1

Related Questions