How to create Recoil MutableSnapshot?

1.5k views Asked by At

According to the Docs, https://recoiljs.org/docs/api-reference/core/RecoilRoot

<RecoilRoot> accept props as initializeState?: (MutableSnapshot => void) signature.
That able to initialize Recoil State so I want to use this props but I don't understand how to make MutableSnapshot object.

import {RecoilRoot} from 'recoil';

function AppRoot() {
  return (
    <RecoilRoot initializeState={/* How to setup arguments here? */} >
      <ComponentThatUsesRecoil />
    </RecoilRoot>
  );
}

On the other hand Snapshot is easier to get from useRecoilSnapshot() though.

1

There are 1 answers

0
Laststance On BEST ANSWER

I figure out answer of the question myself. MutableSnapshot is passed by Recoil library code automatically so user don't have to create MutableSnapshot object yourself.

Bellow code is typically usage of initializeState. Pick argument you need (set, get etc) form MutableSnapshot with object destructuring then write your state initialization code.

  render(
    <RecoilRoot
      initializeState={({ set }: MutableSnapshot): void =>
        set(recoilState, initialRecoilStateValue)
      }
    >
      {ui}
    </RecoilRoot>
  )