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
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