Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update Recoil JS Atom Object

I have an Atom object defined like this:

export const walletInfo = atom({
  key: "walletInfo",
  default: {
    connected: false,
    someString: "",
    someInt: 0,
    someOtherInfo: "",
  },
});

The question is, how do I change only single value in Atom object without overwriting everything else? For example, how do I set connected: true and keep the rest of the information?

The code below will "erase" the rest of the object

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import { walletInfo } from "../src/atoms";
const [wallet, setWallet] = useRecoilState(walletInfo);

setWallet({
   connected: true,
});

>Solution :

You need to combine the previous state and updated state like this

setWallet((prevState) => ({
   ...prevState,
   connected: true,
}));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading