Skip to content

Commit

Permalink
Update initialize-atom-on-render.mdx (#2280)
Browse files Browse the repository at this point in the history
* Update initialize-atom-on-render.mdx

Added a Typescript example for useHydrateAtoms

* run prettier and resolve comments
  • Loading branch information
ioExpander authored Dec 28, 2023
1 parent 1198f35 commit f602d74
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions docs/guides/initialize-atom-on-render.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,48 @@ This behavior is due to our child components looking for the lowest commmon `Pro
For more information on `Provider` behavior, please read the docs [here](../core/provider.mdx).

For more complex use cases, check out [Scope extension](../extensions/scope.mdx).

### Using Typescript

`useHydrateAtoms` has overloaded types and typescript cannot extract types from overloaded function. It is recommended to use a `Map` when passing initial atom values to the `useHydrateAtoms`.

Here is a working example:

```tsx
import type { ReactNode } from 'react'
import { Provider, atom, useAtomValue } from 'jotai'
import type { WritableAtom } from 'jotai'
import { useHydrateAtoms } from 'jotai/utils'

const testAtom = atom('')

export default function App() {
return (
<Provider>
<AtomsHydrator atomValues={[[testAtom, 'hello']]}>
<Component />
</AtomsHydrator>
</Provider>
)
}

//This component contains all the states and the logic
function Component() {
const testAtomValue = useAtomValue(testAtom)
return <div>{testAtomValue}</div>
}

function AtomsHydrator({
atomValues,
children,
}: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
atomValues: Iterable<
readonly [WritableAtom<unknown, [any], unknown>, unknown]
>
children: ReactNode
}) {
useHydrateAtoms(new Map(atomValues))
return children
}
```

1 comment on commit f602d74

@vercel
Copy link

@vercel vercel bot commented on f602d74 Dec 28, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.