Created
June 23, 2022 13:13
-
-
Save mupkoo/eeebc666b2836b1f0f6c6467909a9966 to your computer and use it in GitHub Desktop.
useAsyncEffect
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, { useEffect, useState } from "react"; | |
export default function App() { | |
const [count, setCount] = useState(1); | |
const [autoCount, setAutoCount] = useState(1); | |
useAsyncEffect( | |
function* () { | |
while (true) { | |
yield new Promise((resolve) => setTimeout(resolve, 1000)); | |
setAutoCount((n) => n + count); | |
} | |
}, | |
[count] | |
); | |
return ( | |
<div className="App"> | |
<h1>Hello CodeSandbox</h1> | |
<h2>Start editing to see some magic happen!</h2> | |
<span> | |
Count: {count}, Autocount: {autoCount} | |
</span> | |
<div> | |
<button | |
type="button" | |
onClick={() => { | |
setCount((n) => n + 1); | |
setAutoCount(1); | |
}} | |
> | |
Increment | |
</button> | |
</div> | |
</div> | |
); | |
} | |
const useAsyncEffect = (callback, deps) => { | |
useEffect(() => { | |
let canceled = false; | |
const gen = callback(); | |
const loop = async () => { | |
const { value, done } = gen.next(); | |
await value; | |
if (!done && !canceled) { | |
loop(); | |
} | |
}; | |
loop(); | |
return () => void (canceled = true); | |
}, deps); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment