Recoil asynchronous Issue

Viewed 58

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: "testk@gmail.com" };
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

1 Answers

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: "testk@gmail.com" };
    setUserInfo((prev) => ({ ...prev, ...s }));

    const s2 = { name: "AJH" };
    setUserInfo((prev) => ({ ...prev, ...s2 }));
  }
Related