From 2f7b6571f27563602140b4ebef772bdb83e909f9 Mon Sep 17 00:00:00 2001 From: Matchu Date: Fri, 23 Apr 2021 11:48:38 -0700 Subject: [PATCH] Fix loop in useFetch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Oops, my recent change made it so `useFetch` started re-requesting stuff in an infinite loop 😅 right, this is how effects work, lol! --- src/app/util.js | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/app/util.js b/src/app/util.js index 712310e..0a26e09 100644 --- a/src/app/util.js +++ b/src/app/util.js @@ -238,10 +238,15 @@ export function useFetch(url, { responseType, ...fetchOptions }) { const [error, setError] = React.useState(null); const [data, setData] = React.useState(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 + // of an identical object! + const fetchOptionsAsJson = JSON.stringify(fetchOptions); + React.useEffect(() => { let canceled = false; - fetch(url, fetchOptions) + fetch(url, JSON.parse(fetchOptionsAsJson)) .then(async (res) => { if (canceled) { return; @@ -265,7 +270,7 @@ export function useFetch(url, { responseType, ...fetchOptions }) { return () => { canceled = true; }; - }, [url, fetchOptions]); + }, [url, fetchOptionsAsJson]); return { loading, error, data }; }