Can the default value of a recoil atom be an object of objects?

0

Issue

Can I create a recoil atom with default value as an object of object? See the below code for reference.

export const formState = atom({
  key: "formState",
  default: {
    name: {
       firstName: "",
       lastName: ""
    }
  }
});

Solution

Yes, you can. Here’s an example:

TS Playground

import {default as React} from 'react';
import {atom, useRecoilState} from 'recoil';

const formState = atom({
  key: "formState",
  default: {
    name: {
      firstName: "",
      lastName: "",
    },
  },
});

function App (): React.ReactElement {
  const [state, setState] = useRecoilState(formState);

  const updateFirstName = (firstName: string): void => setState(formState => ({
    ...formState,
    name: {
      ...formState.name,
      firstName,
    },
  }));

  const {firstName} = state.name; // string
  return (<div>First name: {firstName}</div>);
}

Answered By – jsejcksn

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More