`fetch('/api/v1/whoami')` is potentially too optimistic
Categories
(developer.mozilla.org Graveyard :: General, enhancement, P1)
Tracking
(Not tracked)
People
(Reporter: peterbe, Unassigned)
References
Details
(Keywords: in-triage, Whiteboard: [specification][type:bug][points=1])
These lines assume that the GET /api/v1/whoami
always works and returns a JSON response.
If the server fails to respond it will try to parse JSON out of something that might not exist.
Two things that can go wrong:
-
The response might be a 502 Bad Gateway from the load balancer. This is likely to be a stock HTML page.
-
The client's internet connection might just fail to load. E.g. you load the page (with SSR) but once that's loaded you lose internet connection and can't load the onload XHR.
Reporter | ||
Comment 1•6 years ago
|
||
Perhaps a better solution is to be prepared to render the "Sign in" icon with an error state. E.g. something like this:
const [userData, setUserData] = useState<?UserData>(null);
const [userDataError, setUserDataError] = useState<?UserData||Response||Ihavenoidea>(null);
useEffect(() => {
fetch('/api/v1/whoami')
.then(response => {
if (response.ok) {
response.json().then(data => {
setUserData({ ... as before ...})
})
} else {
setUserDataError(response)
}
})
.catch(error => {
setUserDataError(error)
})
Clearly, I have no idea how Flow works :)
But equipped with the userDataError
we can display something to the user akin to "Sorry, can't check if you're logged in".
It's important to appreciate that this hypothetical userDataError
can either be a fetch Response
or it can be an exception. I don't know how best to deal with this in detail. You can inspect it in and find out if the error is an exception or a failed Response object.
See https://www.peterbe.com/plog/displaying-fetch-errors-in-react for potential inspiration if it helps at all.
Updated•6 years ago
|
Updated•6 years ago
|
Updated•6 years ago
|
Comment 2•5 years ago
|
||
Updated•5 years ago
|
Description
•