Last active
June 4, 2021 22:29
-
-
Save trae410/b00c690c670fe30ccacc49eb1ecd0d70 to your computer and use it in GitHub Desktop.
React sucks?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect } from 'react' | |
const App = () => { | |
const [docs, setDocs] = useState(null) | |
const [isFetchingDocs, setIsFetchingDocs] = useState(false) | |
const userId = "user123" | |
const getDocs = (userId) => { | |
// some async functoin | |
console.log("function getDocs ran") | |
} | |
useEffect(() => { | |
let isMounted = true | |
if (!isFetchingDocs && userId) { | |
( | |
async () => { | |
try { | |
setIsFetchingDocs(true) | |
const response = await getDocs(userId) | |
// prevent memory leaks, only set docs if isMounted | |
if (isMounted) { | |
setDocs(docs => { | |
if (!docs) { | |
return response | |
} else return docs | |
}) | |
setIsFetchingDocs(false) | |
} | |
} catch (err) { | |
setIsFetchingDocs(false) | |
console.log(err) | |
} | |
} | |
)() | |
} | |
return () => { | |
isMounted = false | |
} | |
}, [ | |
userId, | |
getDocs, | |
setIsFetchingDocs, | |
setDocs | |
]) | |
return ( | |
<ul> | |
{ | |
isFetchingDocs ? <li>...loading</li> | |
: | |
docs.map(doc => { | |
return <li>{doc.name}</li> | |
} | |
} | |
</ul> | |
) | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My mistake was tracking if the component was mounted within a useEffect that set the isFetchingDocs state. I ended up using a separate useEffect with an empty dependency array that set a isMounted useRef variable. I then had a the fetching function within the component but as a pure funtion that set the isFetching state, fetched the data then set the data and isFetchingDocs to false if the isMounted was true. Ended up with one fetch call, no memory leak warnings and no eslint warnings :) it is a bit cumbersome to do all of this just to fetch some data though... Maybe it would be better to fetch the data outside of a useEffect?