Search code examples
reactjstypescriptrecoiljs

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


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>);
    }