Answers
- There are two problems with the implementation:
useEffect
doesn’t support top-levelasync
/await
- If the component is umounted during the HTTP request, an error will occur when the
data
state is set
Here is an implementation with those issues resolved:
useEffect(() => { let cancel = false; fetch('https://some-rest-api/') .then((response) => data.json()) .then((data) => { if (!cancel) { setData(data); } }); return () => { cancel = true; }; }, []);
- An
assert
function can be used on the response body object as follows:export async function getFirstNames() {
const response = await fetch('https://some- firstnames/');
const body = await response...