use-http
use-http copied to clipboard
When using managed state with async/await, 'error' and 'request.error' are initially out of sync
Describe the bug
When using managed state, if an error occurs in an async function for the first time, error is initially undefined while request.error immediately contains the expected error.
Upon calling the problematic async function again, they are both defined, and match. Is this expected behaviour or a bug?
Backstory: I had a bug in my server causing it to 500 on every request, and saw out that my frontend wasn't noticing the first server error properly, but was reacting to the second and subsequent. As a band-aid, I changed from checking error to request.error and things are working as expected. However, I don't understand why this band-aid was necessary, and expect others may run into the same situation.
I've created a trivial example on Codesandbox.
⚠️ Make a Codesandbox ⚠️ https://codesandbox.io/s/keen-cloud-m1x3k?file=/src/App.js
To Reproduce Steps to reproduce the behavior:
- Click 'submit', you'll see in the console that the first time after the await post call,
erroris undefined whilerequest.erroris defined - Click 'submit' again, they'll both be defined
Expected behavior They should both be defined the first time, right?
OK, I couldn't find anything about this in text form (my preference), but after submitting this issue I finally watched the video tutorial for managed state which explained why I was getting stale values: request.error is a getter which will always pull from the current error ref, whereas plain old error can get stale between renders.
Can we update the README for managed state with a warning? I think because the provided example in the docs exposes error, with no mention of staleness, I just assumed that's what I should be using.
I will accept a PR! :)