Search code examples
reactjsrecoiljs

Recoil asynchronous Issue


I am a novice at Recoil. I have a question about Recoil asynchronous

In case of below code

    const usersState = atom({
      key: "userInfo",
      default: { email: "", name: "" }
    });

First, if I have to update the name of userInfo first

const [userInfo, setUserInfo] = useRecoilState(usersState);
const s = { email: "[email protected]" };
setUserInfo({ ...userInfo, ...s });

And then update name of userInfo

 const s2 = { name: "AJH" };
 setUserInfo({ ...userInfo, ...s2 });

How can I achieve that? I took a look at atom effect, sync effect on recoil homepage, but I don't understand how to use it

my full code is at CodeSandbox

please give me a any idea


Solution

  • Setting state is an asynchronous action. You can however use a callback function to take the current value into account:

      function handleClick() {
        const s = { email: "[email protected]" };
        setUserInfo((prev) => ({ ...prev, ...s }));
    
        const s2 = { name: "AJH" };
        setUserInfo((prev) => ({ ...prev, ...s2 }));
      }