Requests in an Effect
What this is. A request is exactly the kind of outside system an effect is for. Ask for the data, and set state when it arrives.
The thing about fetch that surprises everyone. It does not reject on 404 or 500. A response is a response, even when it is an error page. If you do not check res.ok yourself, you will hand an HTML error page to res.json() and get a parse error that says nothing about what actually happened.
Requests come back out of order. Type a query, then change it. The first request may well answer after the second. Without a guard you display results for a query nobody is looking at any more.
The fix is a flag the cleanup sets, so a response that arrives after the component moved on is ignored. AbortController is the fuller version: it also stops the request rather than ignoring the answer.
✦ There are no secrets in frontend code
Anything in your bundle is readable by every visitor, whatever the variable is called. Use an API that allows public keys with a domain restriction, or route the request through a server you control. A key committed to a public repository has to be rotated, not deleted.
Mark this lesson complete
Signed in, your progress follows you to every device.