Skip to content

Instantly share code, notes, and snippets.

@mupkoo
Created June 23, 2022 13:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mupkoo/eeebc666b2836b1f0f6c6467909a9966 to your computer and use it in GitHub Desktop.
Save mupkoo/eeebc666b2836b1f0f6c6467909a9966 to your computer and use it in GitHub Desktop.
useAsyncEffect
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