"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.
This commit is contained in:
@@ -1,30 +1,26 @@
|
|||||||
import React, { useState, useEffect } from 'react';
|
import React, { useState, useEffect, useRef } from 'react';
|
||||||
import dateFormat from 'dateformat';
|
import dateFormat from 'dateformat';
|
||||||
|
|
||||||
const NewsFeed = props => {
|
const NewsFeed = props => {
|
||||||
const [articles, setArticles] = useState([]);
|
const [articles, setArticles] = useState([]);
|
||||||
|
const aborter = useRef(new AbortController()); //BUGFIX: double-renders = double fetches + react update after unmount
|
||||||
|
|
||||||
useEffect(async () => {
|
useEffect(() => {
|
||||||
if (articles.length != 0) { //BUGFIX: There's an extra render called on unmounted components somewhere
|
//this... um...
|
||||||
return;
|
fetch(`${process.env.NEWS_URI}/news`, {
|
||||||
}
|
|
||||||
|
|
||||||
//NOTE: could this be improved with useMemo?
|
|
||||||
const result = await fetch(`${process.env.NEWS_URI}/news`, {
|
|
||||||
method: 'GET',
|
method: 'GET',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
'Access-Control-Allow-Origin': '*'
|
'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) {
|
return () => aborter.current.abort(); //This is an ugly, ugly solution, but it's the only one that works
|
||||||
const err = `${result.status}: ${await result.text()}`;
|
|
||||||
console.log(err);
|
|
||||||
alert(err);
|
|
||||||
} else {
|
|
||||||
setArticles(await result.json());
|
|
||||||
}
|
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
|||||||
Reference in New Issue
Block a user