Last active
September 15, 2021 20:33
-
-
Save bartdorsey/0170ad43ce7c152a1a9a4538f412e343 to your computer and use it in GitHub Desktop.
useAsyncEffect - Like useEffect but without an Async IIFE
This file contains 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 { useEffect } from 'react'; | |
export default function useAsyncEffect(callback, dependencies) { | |
useEffect(() => { | |
(async() => { | |
return await callback(); | |
})(); | |
}, dependencies); | |
} | |
// How to use this. | |
// const App = () => { | |
// const [users, setUsers] = useState([]); | |
// | |
// useAsyncEffect(async () => { | |
// const response = await fetch('/api/users'); | |
// const users = await response.json(); | |
// setUsers(users); | |
// return () => { | |
// console.log("This is cleanup"); | |
// } | |
// },[]); | |
// | |
// return ( | |
// <Users users={users}/> | |
// ); | |
//} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment