Back to Jotai

Relay

docs/extensions/relay.mdx

2.19.12.2 KB
Original Source

You can use Jotai with Relay.

Install

You have to install jotai-relay and relay-runtime.

npm install jotai-relay relay-runtime

Usage

See Relay Docs to learn about basics and how to use compiler in advance.

atomWithQuery

atomWithQuery creates a new atom with fetchQuery.

jsx
import React, { Suspense } from 'react'
import { Provider, useAtom } from 'jotai'
import { useHydrateAtoms } from 'jotai/utils'
import { environmentAtom, atomWithQuery } from 'jotai-relay'
import { Environment, Network, RecordSource, Store } from 'relay-runtime'
import graphql from 'babel-plugin-relay/macro'

const myEnvironment = new Environment({
  network: Network.create(async (params, variables) => {
    const response = await fetch('https://countries.trevorblades.com/', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        query: params.text,
        variables,
      }),
    })
    return response.json()
  }),
  store: new Store(new RecordSource()),
})

const countriesAtom = atomWithQuery(
  graphql`
    query AppCountriesQuery {
      countries {
        name
      }
    }
  `,
  () => ({}),
)

const Main = () => {
  const [data] = useAtom(countriesAtom)
  return (
    <ul>
      {data.countries.map(({ name }) => (
        <li key={name}>{name}</li>
      ))}
    </ul>
  )
}

const HydrateAtoms = ({ children }) => {
  useHydrateAtoms([[environmentAtom, myEnvironment]])
  return children
}

const App = () => {
  return (
    <Provider>
      <HydrateAtoms>
        <Suspense fallback="Loading...">
          <Main />
        </Suspense>
      </HydrateAtoms>
    </Provider>
  )
}

Examples

<Stackblitz id="vitejs-vite-divyhe" file="src%2FApp.tsx" />

atomWithMutation

atomWithMutation creates a new atom with commitMutation.

FIXME: add code example and codesandbox

atomWithSubscription

atomWithSubscription creates a new atom with requestSubscription.

FIXME: add code example and codesandbox