7

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: 'foo@bar.com', userId: getRand());
Yoav Kadosh
  • 4,807
  • 4
  • 39
  • 56
Kirk Ross
  • 6,413
  • 13
  • 61
  • 104

2 Answers2

4

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: 'foo@bar.com', 
  userId: getRand()
});
Yoav Kadosh
  • 4,807
  • 4
  • 39
  • 56
king.reflex
  • 313
  • 4
  • 10
  • How about merging previous userstate with spread operator and change part of the propery with a new value? How to change the state in a selector instead using setState? – Eko Andri Jul 30 '21 at 09:22
1

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: "foo@bar.com", userId: Math.random() });
  };

Working Demo

CodeSandbox

HaveSpacesuit
  • 3,572
  • 6
  • 40
  • 59
A.R.SEIF
  • 865
  • 1
  • 7
  • 25