Skip to content

Instantly share code, notes, and snippets.

@trae410
Last active June 4, 2021 22:29
Show Gist options
  • Save trae410/b00c690c670fe30ccacc49eb1ecd0d70 to your computer and use it in GitHub Desktop.
Save trae410/b00c690c670fe30ccacc49eb1ecd0d70 to your computer and use it in GitHub Desktop.
React sucks?
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
@trae410
Copy link
Author

trae410 commented Jun 4, 2021

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?

@trae410
Copy link
Author

trae410 commented Jun 4, 2021

Solution gist here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment