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
Solution gist here