useAsyncState
installation
To get started with useAsyncState, you can install it via npm or yarn:
npm install @ravvi-kumar/use-async-state
or
yarn add @ravvi-kumar/use-async-state
Types declarations are included in the package
✨
Usage
using Async await
here is an example by using async-await
:
convert your function to async function , put await keyword in front of setter function . the setter function returns the promise of the latest state , you can store it inside a variable and immediately use it right away .
import { useAyncState } from "@ravvi-kumar/use-async-state";
function Counter() {
const [count, setCount] = useAsyncState(0);
async function increment() {
const latestCount=await setCount(count + 1);
console.log(latestCount) // here we will get latest value
}
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
using promise chaining
here is an example by using promise-chainig
:
the setter function returns the promise of the latest state , you can grab the latest state by chaining
then( )
function method .
import { useAyncState } from "@ravvi-kumar/use-async-state";
function Counter() {
const [count, setCount] = useAsyncState(0);
function increment() {
setCount(count + 1).then(latestCount=>{
console.log(latestCount) // here we will get latest value
})
}
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}