From 19f5c200567a6de66fee74f340155e8f5a52561e Mon Sep 17 00:00:00 2001 From: Kayne Ruse Date: Sun, 28 Mar 2021 04:38:03 +1100 Subject: [PATCH] "Fixed" errors on logout, read more I really don't like this solution. The problem was caused by fetch being called twice after the component was rendered twice. I don't know why it renders twice. --- client/components/panels/news-feed.jsx | 28 +++++++++++--------------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/client/components/panels/news-feed.jsx b/client/components/panels/news-feed.jsx index d2389c8..7bde952 100644 --- a/client/components/panels/news-feed.jsx +++ b/client/components/panels/news-feed.jsx @@ -1,30 +1,26 @@ -import React, { useState, useEffect } from 'react'; +import React, { useState, useEffect, useRef } from 'react'; import dateFormat from 'dateformat'; const NewsFeed = props => { const [articles, setArticles] = useState([]); + const aborter = useRef(new AbortController()); //BUGFIX: double-renders = double fetches + react update after unmount - useEffect(async () => { - if (articles.length != 0) { //BUGFIX: There's an extra render called on unmounted components somewhere - return; - } - - //NOTE: could this be improved with useMemo? - const result = await fetch(`${process.env.NEWS_URI}/news`, { + useEffect(() => { + //this... um... + fetch(`${process.env.NEWS_URI}/news`, { method: 'GET', headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' }, - }); + signal: aborter.current.signal //oh dear + }) + .then(blob => blob.json()) + .then(json => setArticles(json)) + .catch(e => null) //swallow errors + ; - if (!result.ok) { - const err = `${result.status}: ${await result.text()}`; - console.log(err); - alert(err); - } else { - setArticles(await result.json()); - } + return () => aborter.current.abort(); //This is an ugly, ugly solution, but it's the only one that works }, []); return (