1
const _id = match.params.id;
const response = await api.get("/roleidindex", {
  params: {
    _id
  }
})

console.log (response.data); //correct object
setRole(response.data);
console.log (role); //{}

In my code I have this piece of text and, as the comments show the response from the request are fine, but when I set the state to the value, the state remains the same as its initial one. That is all inside a useEffect method, by the way.

Brian Thompson
  • 13,263
  • 4
  • 23
  • 43
Capeudinho
  • 33
  • 1
  • 6
  • 1
    It helps if you show more code. Like where you initialize state etc. – Moshe Sommers May 15 '20 at 19:58
  • @BrianThompson Thanks for your answer. I see, then. What do you recommend doing, in that case? – Capeudinho May 15 '20 at 19:58
  • You are logging a [stale closure](https://dmitripavlutin.com/react-hooks-stale-closures/) it would help if you know how closures and hooks work. Async is not what causing the "wrong log" you can put that log in a timeout and log it next year and it'll still log the old value. – HMR May 15 '20 at 20:01
  • @BrianThompson Async is not what causing the "wrong log" you can put that log in a timeout and log it next year and it'll still log the old value. – HMR May 15 '20 at 20:01
  • @BrianThompson The answer of the other question only helped so much. I made so that role state had an initial value of {name : ""} so that its name could be used in the JSX part of the code while it didn't have the correct name. But the "Cannot read property 'name' of null" still appears. By the way, I put a console.log in the JSX right before the name element and for the three times it showed something, it showed only the correct object, never null. – Capeudinho May 15 '20 at 20:24
  • Actually, I think I found a way with conditional rendering. – Capeudinho May 15 '20 at 20:46

1 Answers1

2

When a state change is called, components do not update immediately - rather, changes are batched such that all queued changes are done at once, and then re-rendering occurs.

With hooks, the role variable in your code will never receive the updated data anyway, because the whole component will have to be called again for the updated value to exist - only in that next call of the component will the role be assigned the updated value taken from useState.

If you want to log the data, assuming it starts out empty, you should do so in the main component body:

const [role, setRole] = useState(null);
if (role) {
  console.log('Got data', role);
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320