Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.