0

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: ""
    }
  }
});
  • See [my answer](https://stackoverflow.com/a/70692453/438273). Note: there's a missing `}` before the closing parentheses in your example. – jsejcksn Jan 13 '22 at 06:47

1 Answers1

0

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>);
}
jsejcksn
  • 27,667
  • 4
  • 38
  • 62
  • Thanks for you response. When I tried to update formState using setFormState({ ...formState, formState.name.firstName: "first name' }), I couldn't and the compiler is giving an error on formState.name.firstName. – Manish Kumar Jan 13 '22 at 06:57
  • @ManishKumar I added an example of how to change just the `firstName` in the nested state object. Does this answer your question? – jsejcksn Jan 13 '22 at 07:06