Oops, I broke valids!

Ah right, React state batching doesn't always work how I expect it to. The separate state caused the hook to return and cache `{loading: false, error: null, data: null}`, and then on a _later_ tick the data value showed up, but only _after_ the response was already cached!

This broken a bunch of species/color picker stuff, now it's fixed!
This commit is contained in:
Emi Matchu 2021-06-11 08:31:01 -07:00
parent eaa4fbb575
commit ddd562b672

View file

@ -248,9 +248,11 @@ export function useFetch(url, { responseType, skip, ...fetchOptions }) {
throw new Error(`unsupported responseType ${responseType}`); throw new Error(`unsupported responseType ${responseType}`);
} }
const [loading, setLoading] = React.useState(skip ? false : true); const [response, setResponse] = React.useState({
const [error, setError] = React.useState(null); loading: skip ? false : true,
const [data, setData] = React.useState(null); error: null,
data: null,
});
// We expect this to be a simple object, so this helps us only re-send the // We expect this to be a simple object, so this helps us only re-send the
// fetch when the options have actually changed, rather than e.g. a new copy // fetch when the options have actually changed, rather than e.g. a new copy
@ -271,18 +273,14 @@ export function useFetch(url, { responseType, skip, ...fetchOptions }) {
} }
const arrayBuffer = await res.arrayBuffer(); const arrayBuffer = await res.arrayBuffer();
setLoading(false); setResponse({ loading: false, error: null, data: arrayBuffer });
setError(null);
setData(arrayBuffer);
}) })
.catch((error) => { .catch((error) => {
if (canceled) { if (canceled) {
return; return;
} }
setLoading(false); setResponse({ loading: false, error, data: null });
setError(error);
setData(null);
}); });
return () => { return () => {
@ -290,7 +288,7 @@ export function useFetch(url, { responseType, skip, ...fetchOptions }) {
}; };
}, [skip, url, fetchOptionsAsJson]); }, [skip, url, fetchOptionsAsJson]);
return { loading, error, data }; return response;
} }
/** /**