@sanity/react-loader

npm install @sanity/react-loader @sanity/client react@^18.2
Usage
Server only production data fetching, client side Live Mode
By default data is fetched on both the server, and on the client after hydration.
For private datasets, or other similar use cases, it may be desirable to only fetch data on the server when Live Mode is not enabled.
For this to work you'll first have to setup a shared file that is loaded both on the server and the client, which sets ssr: true and defers setting the client to later by setting client: false. The snippets are for a Remix application
import {createQueryStore} from '@sanity/react-loader'
export const {
loadQuery,
setServerClient,
useQuery,
useLiveMode,
} = createQueryStore({client: false, ssr: true})
You can also use the top-level shortcuts for the same effect:
export {
loadQuery,
setServerClient,
useQuery,
useLiveMode,
} from '@sanity/react-loader'
Later in the server side of the app, you setup the client. The .server.ts suffix on Remix ensures that this file is only loaded on the server, and it avoids adding @sanity/client to the browser bundle in production.
import {createClient} from '@sanity/client'
import {loadQuery, setServerClient} from './sanity.loader'
const client = createClient({
projectId: process.env.SANITY_PROJECT_ID,
dataset: process.env.SANITY_DATASET,
useCdn: true,
apiVersion: process.env.SANITY_API_VERSION,
stega: {
enabled: true,
studioUrl: 'https://my.sanity.studio',
},
})
setServerClient(client)
export {loadQuery}
Then somewhere in your app, you can use the loadQuery and useQuery utilities together. useQuery now only fetches data when Live Mode is active. Otherwise it's loadQuery that is used.
import {json, type LoaderFunction} from '@remix-run/node'
import {Link, useLoaderData, useParams} from '@remix-run/react'
import {useQuery} from '~/sanity.loader'
import {loadQuery} from '~/sanity.loader.server'
interface Product {}
const query = `*[_type == "product" && slug.current == $slug][0]`
export const loader: LoaderFunction = async ({params}) => {
return json({
params,
initial: await loadQuery<Product>(query, params),
})
}
export default function ProductPage() {
const {params, initial} = useLoaderData<typeof loader>()
if (!params.slug || !initial.data?.slug?.current) {
throw new Error('No slug, 404?')
}
const {data} = useQuery<Product>(query, params, {initial})
return <ProductTemplate data={data} />
}
Enabling Live Mode is done by adding useLiveMode to the same component you're currently calling enableVisualEditing from @sanity/visual-editing:
import {enableVisualEditing, type HistoryUpdate} from '@sanity/visual-editing'
import {useLiveMode} from '~/sanity.loader'
import {useEffect} from 'react'
const client = createClient({
projectId: window.ENV.SANITY_PROJECT_ID,
dataset: window.ENV.SANITY_DATASET,
useCdn: true,
apiVersion: window.ENV.SANITY_API_VERSION,
stega: {
enabled: true,
studioUrl: 'https://my.sanity.studio',
},
})
export default function VisualEditing() {
useEffect(
() =>
enableVisualEditing({
history: {
},
}),
[],
)
useLiveMode({client})
return null
}
Adding overlays to any element
You can use the encodeDataAttribute function returned by useQuery to create data-sanity attributes, that are picked up by @sanity/visual-editing.
This allows you to link to elements that otherwise isn't automatically linked to using @sanity/client, such as array root item, or an image field.
If you aren't using stega and don't have a studioUrl defined in the createClient call, then you add it to the useLiveMode hook:
-useLiveMode({ client })
+useLiveMode({ client, studioUrl: 'https://my.sanity.studio' })
You then use it in your template:
import {json, type LoaderFunction} from '@remix-run/node'
import {Link, useLoaderData, useParams} from '@remix-run/react'
import {useQuery} from '@sanity/react-loader'
import {loadQuery} from '~/sanity.loader.server'
interface Product {}
const query = `*[_type == "product" && slug.current == $slug][0]`
export const loader: LoaderFunction = async ({params}) => {
return json({
params,
initial: await loadQuery<Product>(query, params),
})
}
export default function ProductPage() {
const {params, initial} = useLoaderData<typeof loader>()
if (!params.slug || !initial.data?.slug?.current) {
throw new Error('No slug, 404?')
}
const {data, encodeDataAttribute} = useQuery<Product>(query, params, {
initial,
})
return <ProductTemplate data={data} encodeDataAttribute={encodeDataAttribute} />
}
You use encodeDataAttribute by giving it a path to the data you want to be linked to, or open in the Studio when in the Presentation tool.
import {EncodeDataAttributeCallback} from '@sanity/react-loader'
interface Product {}
interface Props {
data: Product
encodeDataAttribute: EncodeDataAttributeCallback
}
export default function ProductTemplate(props: Props) {
const {data, encodeDataAttribute} = props
return (
<>
<img
// Adding this attribute makes sure the image is always clickable in the Presentation tool
data-sanity={encodeDataAttribute('image')}
src={urlFor(data.image.asset).url()}
// other props
/>
</>
)
}