From ddd562b672767ed34b9e2bf02134df63d70e9b66 Mon Sep 17 00:00:00 2001 From: Matchu Date: Fri, 11 Jun 2021 08:31:01 -0700 Subject: [PATCH] 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! --- src/app/util.js | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/app/util.js b/src/app/util.js index 59f7772..88ae8cc 100644 --- a/src/app/util.js +++ b/src/app/util.js @@ -248,9 +248,11 @@ export function useFetch(url, { responseType, skip, ...fetchOptions }) { throw new Error(`unsupported responseType ${responseType}`); } - const [loading, setLoading] = React.useState(skip ? false : true); - const [error, setError] = React.useState(null); - const [data, setData] = React.useState(null); + const [response, setResponse] = React.useState({ + loading: skip ? false : true, + error: null, + data: null, + }); // 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 @@ -271,18 +273,14 @@ export function useFetch(url, { responseType, skip, ...fetchOptions }) { } const arrayBuffer = await res.arrayBuffer(); - setLoading(false); - setError(null); - setData(arrayBuffer); + setResponse({ loading: false, error: null, data: arrayBuffer }); }) .catch((error) => { if (canceled) { return; } - setLoading(false); - setError(error); - setData(null); + setResponse({ loading: false, error, data: null }); }); return () => { @@ -290,7 +288,7 @@ export function useFetch(url, { responseType, skip, ...fetchOptions }) { }; }, [skip, url, fetchOptionsAsJson]); - return { loading, error, data }; + return response; } /**