Relay
You can use Jotai with Relay.
Install
Section titled “Install”You have to install jotai-relay and relay-runtime.
npm install jotai-relay relay-runtimeSee Relay Docs to learn about basics and how to use compiler in advance.
atomWithQuery
Section titled “atomWithQuery”atomWithQuery creates a new atom with fetchQuery.
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
Section titled “Examples”atomWithMutation
Section titled “atomWithMutation”atomWithMutation creates a new atom with commitMutation.
FIXME: add code example and codesandbox
atomWithSubscription
Section titled “atomWithSubscription”atomWithSubscription creates a new atom with requestSubscription.
FIXME: add code example and codesandbox