0.1.1 • Published 5 years ago

use-async-setstate v0.1.1

Weekly downloads
94
License
MIT*
Repository
-
Last release
5 years ago

use-async-setState

NPM Build Status

setState returned by useState does not take a callback anymore, but this is sometimes convenient to chain setState calls one after the other.

import { useAsyncSetState } from "use-async-setState";

const Comp = () => {
  const [state,setStateAsync] = useAsyncSetState({ counter: 0 });
  
  const incrementAsync = async () => {
    await setStateAsync(s => ({...s: counter: s.counter+1}));
  }
  
  return <div>...</div> 
}   

Reading your own writes in async closures

Even if your component has updated after promise resolution, the async closure being currently executed remains the same and variables captured in it remains updated.

If your async closure need access to the current state, you can use useGetState which will use a ref to return you the up-to-date state.

import { useAsyncSetState, useGetState } from "use-async-setState";

const Comp = () => {
  const [state,setStateAsync] = useAsyncSetState({ counter: 0 });
  const getState = useGetState(state);
  
  const incrementTwiceAndSubmit = async () => {
    await setStateAsync({...getState(): counter: getState().counter + 1});
    await setStateAsync({...getState(): counter: getState().counter + 1});
    await submitState(getState());
  }
  
  return <div>...</div> 
}   

License

MIT

Hire a freelance expert

Looking for a React/ReactNative freelance expert with more than 5 years production experience? Contact me from my website or with Twitter.