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

Solution gist here

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