Using fetch in useEffect and checking if the component is mounted before setting state
@gaearon ci sta già lavorando.
Dal 11/3/2020.
- Lingua principale
- JavaScript
- Stelle
- 11.8k
- Fork
- 7.9k
- Merge medio
- 1g 11h
- PR unite (30g)
- 11
Descrizione
Consider the following code:
const useIsMounted = () => {
const isMounted = React.useRef(false);
React.useEffect(() => {
isMounted.current = true;
return () => isMounted.current = false;
}, []);
return isMounted;
};
And the effect:
const [result, setResult] = React.useState({
loading: true,
data: []
})
const isMounted = useIsMounted();
React.useEffect(() => {
console.log('in effect')
fetch('https://jsonplaceholder.typicode.com/todos')
.then(result => result.json())
.then(data => {
//before setting state in async function you should
// check if the component is still mounted
isMounted.current && setResult({ loading: false, data })
})
},[isMounted])
This code will start a discussion about this being an anti pattern. I think that it's comparing apples with oranges and that article does not apply here.
The useEffect clean up examples show a situation where variables in the callback's closure don't go out of scope and can cause a memory leak but the fetch example won't have that problem.
Is it possible to provide examples of how to safely combine setting state with asynchronous fetch result while not setting it on unmounted components?
It is possible to cancel a fetch (maybe in all browser with the correct babel configuration) but when using SSR (like next.js) and using something like isomorphic-fetch then this is not an option.
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Valutazione
Questa issue non è ancora stata valutata.