Skip to content

Instantly share code, notes, and snippets.

@dance2die
Last active September 11, 2021 09:56
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dance2die/00383f3d98e62099b5ae1eefbd0913b8 to your computer and use it in GitHub Desktop.
Save dance2die/00383f3d98e62099b5ae1eefbd0913b8 to your computer and use it in GitHub Desktop.
function useAsyncState(initialValue) {
const [value, setValue] = useState(initialValue);
const setter = x =>
new Promise(resolve => {
setValue(x);
resolve(x);
});
return [value, setter];
}
function App() {
// const [count, setCount] = useState(0);
// const [message, setMessage] = useState("");
const [count, setCount] = useAsyncState(0);
const [message, setMessage] = useAsyncState("");
function increment() {
setCount(count + 1).then(count => setMessage(`count is ${count}`));
}
function decrement() {
setCount(count - 1).then(count => setMessage(`count is ${count}`));
}
// OR use async/await...
async function increment() {
const newCount = await setCount(count + 1)
setMessage(`count is ${newCount}`);
}
async function decrement() {
const newCount = await setCount(count - 1)
setMessage(`count is ${newCount}`);
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment