Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can the default value of a Recoil atom be an object?

Can I set the default value of a Recoil atom to be an object?

e.g.:

export const currentUserState = atom({
  key: 'currentUserState',
  default: { name: '', email: '', userId: null },
});

And then set it with:

import { currentUserState } from '../atoms/atoms';

const setUserState = useSetRecoilState(currentUserState);
setUserState(name: 'John', email: '[email protected]', userId: getRand());
like image 790
Kirk Ross Avatar asked Oct 17 '20 19:10

Kirk Ross


2 Answers

Yes, It is allowed. Recoil atom state can be an object. You have initialized the atom correctly, but when you set the atom you have to pass an object since the state is object.

Initialize the currentUserState atom

export const currentUserState = atom({
  key: 'currentUserState',
  default: {name: '', email: '', userId: null}
});

and then set the atom state as follows

import {currentUserState} from '../recoilstate/atoms';

const setUserState = useSetRecoilState(currentUserState);

setUserState({
  name: 'John', 
  email: '[email protected]', 
  userId: getRand()
});
like image 171
Deepak Avatar answered Oct 22 '22 07:10

Deepak


Yes, a Recoil atom can be an object.

I have written this code, which you can see below in the working demo.

 const changeValue = () => {
    setUserState({ name: "John", email: "[email protected]", userId: Math.random() });
  };

Working Demo

CodeSandbox

like image 1
A.R.SEIF Avatar answered Oct 22 '22 07:10

A.R.SEIF