@sanity/react-loader
Advanced tools
Comparing version 0.10.0-pink-lizard to 0.11.0-pink-lizard
@@ -15,2 +15,14 @@ # Changelog | ||
## [0.11.0-pink-lizard](https://github.com/sanity-io/visual-editing/compare/react-loader-v0.10.0-pink-lizard...react-loader-v0.11.0-pink-lizard) (2023-11-15) | ||
### ⚠ BREAKING CHANGES | ||
* rename `query` to `loadQuery` | ||
### Bug Fixes | ||
* **docs:** add docs for `encodeDataAttribute` ([0686612](https://github.com/sanity-io/visual-editing/commit/06866126cf019780cce676408a69ac346186c0ec)) | ||
* rename `query` to `loadQuery` ([228dfc3](https://github.com/sanity-io/visual-editing/commit/228dfc3d2c5838d2124302e514ca9530ee92fbb8)) | ||
## [0.10.0-pink-lizard](https://github.com/sanity-io/visual-editing/compare/react-loader-v0.9.2-pink-lizard...react-loader-v0.10.0-pink-lizard) (2023-11-13) | ||
@@ -17,0 +29,0 @@ |
@@ -33,3 +33,3 @@ import type { ClientPerspective } from '@sanity/client' | ||
export declare interface QueryStore { | ||
query: <QueryResponseResult>( | ||
loadQuery: <QueryResponseResult>( | ||
query: string, | ||
@@ -78,12 +78,12 @@ params?: QueryParams, | ||
* and an optional speed optimization if `ssr: false`. | ||
* It's recommended to set `initial` to the return value of `query()`. | ||
* It's recommended to set `initial` to the return value of `loadQuery()`. | ||
* @example | ||
* ```ts | ||
* const queryAuthor = `*[_type == "author" && slug.current == $slug][0]` | ||
* const query = `*[_type == "author" && slug.current == $slug][0]` | ||
* export const getServerSideProps = async ({params}) => { | ||
* const initial = await query<AuhthorType>(queryAuthor, params) | ||
* const initial = await loadQuery<AuhthorType>(query, params) | ||
* return { props: { params, initial } } | ||
* } | ||
* export default function Page({params, initial}) { | ||
* const {data} = useQuery<AuthorType>(queryAuthor, params, {initial}) | ||
* const {data} = useQuery<AuthorType>(query, params, {initial}) | ||
* } | ||
@@ -90,0 +90,0 @@ * ``` |
@@ -1,1 +0,1 @@ | ||
import{createQueryStore as e}from"@sanity/core-loader";import{useState as t,useMemo as r,useEffect as n}from"react";export{u as useEncodeDataAttribute}from"./_chunks/useEncodeDataAttribute-mY2QBNF1.js";const s=s=>{const{createFetcherStore:i,setServerClient:o,enableLiveMode:a,unstable__cache:u,unstable__serverClient:c}=e(s),l={};return{query:async(e,t={},r={})=>{const{perspective:n="published"}=r;if("undefined"!=typeof document)throw new Error("Cannot use `query` in a browser environment, you should use it inside a loader, getStaticProps, getServerSideProps, getInitialProps, or in a React Server Component.");if("published"!==n&&!c.instance)throw new Error('You cannot use other perspectives than "published" unless you set "ssr: true" and call "setServerClient" first.');if("previewDrafts"===n){if(!c.canPreviewDrafts)throw new Error('You cannot use "previewDrafts" unless you set a "token" in the "client" instance you\'re pasing to "setServerClient".');const r=c.instance.config().useCdn?c.instance.withConfig({useCdn:!1}):c.instance,{result:s,resultSourceMap:i}=await r.fetch(e,t,{filterResponse:!1,resultSourceMap:"withKeyArraySelector",perspective:n});return{data:s,sourceMap:i,perspective:n}}const{result:s,resultSourceMap:i}=await u.fetch(JSON.stringify({query:e,params:t}));return i?{data:s,sourceMap:i}:{data:s}},useQuery:(e,s=l,o={})=>{const[a]=t((()=>o.initial?{perspective:"published",...o.initial}:void 0)),u=r((()=>JSON.stringify(s)),[s]),[c,p]=t((()=>i(e,JSON.parse(u),a).value));return n((()=>{const t=i(e,JSON.parse(u),a).listen((e=>{p(e)}));return()=>t()}),[u,a,e]),c},setServerClient:o,useLiveMode:({allowStudioOrigin:e,client:t,onConnect:r,onDisconnect:s})=>{n((()=>{const n=a({allowStudioOrigin:e,client:t,onConnect:r,onDisconnect:s});return()=>n()}),[e,t,r,s])}}};export{s as createQueryStore};//# sourceMappingURL=index.js.map | ||
import{createQueryStore as e}from"@sanity/core-loader";import{useState as t,useMemo as r,useEffect as n}from"react";export{u as useEncodeDataAttribute}from"./_chunks/useEncodeDataAttribute-mY2QBNF1.js";const s=s=>{const{createFetcherStore:i,setServerClient:o,enableLiveMode:a,unstable__cache:u,unstable__serverClient:c}=e(s),l={};return{loadQuery:async(e,t={},r={})=>{const{perspective:n="published"}=r;if("undefined"!=typeof document)throw new Error("Cannot use `loadQuery` in a browser environment, you should use it inside a loader, getStaticProps, getServerSideProps, getInitialProps, or in a React Server Component.");if("published"!==n&&!c.instance)throw new Error('You cannot use other perspectives than "published" unless you set "ssr: true" and call "setServerClient" first.');if("previewDrafts"===n){if(!c.canPreviewDrafts)throw new Error('You cannot use "previewDrafts" unless you set a "token" in the "client" instance you\'re pasing to "setServerClient".');const r=c.instance.config().useCdn?c.instance.withConfig({useCdn:!1}):c.instance,{result:s,resultSourceMap:i}=await r.fetch(e,t,{filterResponse:!1,resultSourceMap:"withKeyArraySelector",perspective:n});return{data:s,sourceMap:i,perspective:n}}const{result:s,resultSourceMap:i}=await u.fetch(JSON.stringify({query:e,params:t}));return i?{data:s,sourceMap:i}:{data:s}},useQuery:(e,s=l,o={})=>{const[a]=t((()=>o.initial?{perspective:"published",...o.initial}:void 0)),u=r((()=>JSON.stringify(s)),[s]),[c,p]=t((()=>i(e,JSON.parse(u),a).value));return n((()=>{const t=i(e,JSON.parse(u),a).listen((e=>{p(e)}));return()=>t()}),[u,a,e]),c},setServerClient:o,useLiveMode:({allowStudioOrigin:e,client:t,onConnect:r,onDisconnect:s})=>{n((()=>{const n=a({allowStudioOrigin:e,client:t,onConnect:r,onDisconnect:s});return()=>n()}),[e,t,r,s])}}};export{s as createQueryStore};//# sourceMappingURL=index.js.map |
@@ -42,3 +42,3 @@ import type { ClientPerspective } from '@sanity/client' | ||
export declare interface QueryStore { | ||
query: <QueryResponseResult>( | ||
loadQuery: <QueryResponseResult>( | ||
query: string, | ||
@@ -81,12 +81,12 @@ params?: QueryParams, | ||
* and an optional speed optimization if `ssr: false`. | ||
* It's recommended to set `initial` to the return value of `query()`. | ||
* It's recommended to set `initial` to the return value of `loadQuery()`. | ||
* @example | ||
* ```ts | ||
* const queryAuthor = `*[_type == "author" && slug.current == $slug][0]` | ||
* const query = `*[_type == "author" && slug.current == $slug][0]` | ||
* export const getServerSideProps = async ({params}) => { | ||
* const initial = await query<AuhthorType>(queryAuthor, params) | ||
* const initial = await loadQuery<AuhthorType>(query, params) | ||
* return { props: { params, initial } } | ||
* } | ||
* export default function Page({params, initial}) { | ||
* const {data} = useQuery<AuthorType>(queryAuthor, params, {initial}) | ||
* const {data} = useQuery<AuthorType>(query, params, {initial}) | ||
* } | ||
@@ -93,0 +93,0 @@ * ``` |
@@ -1,1 +0,1 @@ | ||
import{createQueryStore as e}from"@sanity/core-loader";import{useState as r,useMemo as t,useEffect as n}from"react";export{u as useEncodeDataAttribute}from"../_chunks/useEncodeDataAttribute-mY2QBNF1.js";const o=o=>{const{createFetcherStore:i,enableLiveMode:s}=e(o),c={};return{query:()=>{throw new Error("The `query` function is server only.")},useQuery:(e,o=c,s={})=>{const[u]=r((()=>s.initial?{perspective:"published",...s.initial}:void 0)),a=t((()=>JSON.stringify(o)),[o]),[l,d]=r((()=>i(e,JSON.parse(a),u).value));return n((()=>{const r=i(e,JSON.parse(a),u).listen((e=>{d(e)}));return()=>r()}),[a,u,e]),l},setServerClient:()=>{throw new Error("The `setServerClient` function is server only.")},useLiveMode:({allowStudioOrigin:e,client:r,onConnect:t,onDisconnect:o})=>{n((()=>{const n=s({allowStudioOrigin:e,client:r,onConnect:t,onDisconnect:o});return()=>n()}),[e,r,t,o])}}};export{o as createQueryStore};//# sourceMappingURL=index.js.map | ||
import{createQueryStore as e}from"@sanity/core-loader";import{useState as r,useMemo as t,useEffect as n}from"react";export{u as useEncodeDataAttribute}from"../_chunks/useEncodeDataAttribute-mY2QBNF1.js";const o=o=>{const{createFetcherStore:i,enableLiveMode:s}=e(o),c={};return{loadQuery:()=>{throw new Error("The `loadQuery` function is server only.")},useQuery:(e,o=c,s={})=>{const[u]=r((()=>s.initial?{perspective:"published",...s.initial}:void 0)),a=t((()=>JSON.stringify(o)),[o]),[l,d]=r((()=>i(e,JSON.parse(a),u).value));return n((()=>{const r=i(e,JSON.parse(a),u).listen((e=>{d(e)}));return()=>r()}),[a,u,e]),l},setServerClient:()=>{throw new Error("The `setServerClient` function is server only.")},useLiveMode:({allowStudioOrigin:e,client:r,onConnect:t,onDisconnect:o})=>{n((()=>{const n=s({allowStudioOrigin:e,client:r,onConnect:t,onDisconnect:o});return()=>n()}),[e,r,t,o])}}};export{o as createQueryStore};//# sourceMappingURL=index.js.map |
@@ -1,1 +0,1 @@ | ||
import{createQueryStore as e}from"@sanity/core-loader";const t=t=>{if(!t.ssr)throw new Error("When using React Server Components the `ssr` option must be set to `true`.");const{setServerClient:n,unstable__serverClient:r}=e(t);return{query:async(e,t={},n={})=>{const{perspective:o="published"}=n;if("previewDrafts"===o&&!r.canPreviewDrafts)throw new Error('You cannot use "previewDrafts" unless you set a "token" in the "client" instance you\'re pasing to "setServerClient".');const s="published"!==o||r.instance.config().useCdn||n.cache||n.next?r.instance.config().useCdn?r.instance.withConfig({useCdn:!1}):r.instance:r.instance.withConfig({useCdn:!0}),{result:i,resultSourceMap:c}=await s.fetch(e,t,{filterResponse:!1,cache:n.next?void 0:"no-store",...n,perspective:o});return{data:i,sourceMap:c,perspective:"previewDrafts"===o?o:void 0}},setServerClient:n,useQuery:()=>{throw new Error("The `useQuery` hook can only be called from a client component.")},useLiveMode:()=>{throw new Error("The `useLiveMode` hook can only be called from a client component.")}}},n=()=>{throw new Error("The `useEncodeDataAttribute` hook can only be called from a client component.")};export{t as createQueryStore,n as useEncodeDataAttribute};//# sourceMappingURL=index.react-server.js.map | ||
import{createQueryStore as e}from"@sanity/core-loader";const t=t=>{if(!t.ssr)throw new Error("When using React Server Components the `ssr` option must be set to `true`.");const{setServerClient:n,unstable__serverClient:r}=e(t);return{loadQuery:async(e,t={},n={})=>{const{perspective:o="published"}=n;if("previewDrafts"===o&&!r.canPreviewDrafts)throw new Error('You cannot use "previewDrafts" unless you set a "token" in the "client" instance you\'re pasing to "setServerClient".');const s="published"!==o||r.instance.config().useCdn||n.cache||n.next?r.instance.config().useCdn?r.instance.withConfig({useCdn:!1}):r.instance:r.instance.withConfig({useCdn:!0}),{result:i,resultSourceMap:c}=await s.fetch(e,t,{filterResponse:!1,cache:n.next?void 0:"no-store",...n,perspective:o});return{data:i,sourceMap:c,perspective:"previewDrafts"===o?o:void 0}},setServerClient:n,useQuery:()=>{throw new Error("The `useQuery` hook can only be called from a client component.")},useLiveMode:()=>{throw new Error("The `useLiveMode` hook can only be called from a client component.")}}},n=()=>{throw new Error("The `useEncodeDataAttribute` hook can only be called from a client component.")};export{t as createQueryStore,n as useEncodeDataAttribute};//# sourceMappingURL=index.react-server.js.map |
{ | ||
"name": "@sanity/react-loader", | ||
"version": "0.10.0-pink-lizard", | ||
"version": "0.11.0-pink-lizard", | ||
"homepage": "https://github.com/sanity-io/visual-editing/tree/main/packages/react-loader#readme", | ||
@@ -5,0 +5,0 @@ "bugs": { |
144
README.md
@@ -31,3 +31,3 @@ # @sanity/react-loader | ||
// Used only server side | ||
query, | ||
loadQuery, | ||
setServerClient, | ||
@@ -45,3 +45,3 @@ // Used only client side | ||
import { createClient } from '@sanity/client/stega' | ||
import { setServerClient, query } from './sanity.loader' | ||
import { setServerClient, loadQuery } from './sanity.loader' | ||
@@ -62,6 +62,6 @@ const client = createClient({ | ||
// Re-export for convenience | ||
export { query } | ||
export { loadQuery } | ||
``` | ||
Then somewhere in your app, you can use the `query` and `useQuery` utilities together. `useQuery` now only fetches data when Live Mode is active. Otherwise it's `query` that is used. | ||
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. | ||
@@ -73,7 +73,7 @@ ```tsx | ||
import { json, type LoaderFunction } from '@remix-run/node' | ||
import { query } from '~/sanity.loader.server' | ||
import { loadQuery } from '~/sanity.loader.server' | ||
import { useQuery } from '~/sanity.loader' | ||
interface Product {} | ||
const queryProduct = `*[_type == "product" && slug.current == $slug][0]` | ||
const query = `*[_type == "product" && slug.current == $slug][0]` | ||
@@ -83,3 +83,3 @@ export const loader: LoaderFunction = async ({ params }) => { | ||
params, | ||
initial: await query<Product>(queryProduct, params), | ||
initial: await loadQuery<Product>(query, params), | ||
}) | ||
@@ -95,3 +95,3 @@ } | ||
const { data } = useQuery<Product>(queryProduct, params, { initial }) | ||
const { data } = useQuery<Product>(query, params, { initial }) | ||
@@ -145,2 +145,126 @@ // Use `data` in your view, it'll mirror what the loader returns in production mode, | ||
### Adding overlays to any element | ||
You can use `useEncodeDataAttribute` to create `data-json` attributes, that are picked up by `@sanity/overlays`. | ||
This allows you to link to elements that otherwise isn't automatically linked to using `@sanity/client/stega`, such as array root item, or an image field. | ||
Update your shared loader to change `useQuery`, adding `useEncodeDataAttribute` | ||
```ts | ||
// ./src/app/sanity.loader.ts | ||
import { | ||
createQueryStore, | ||
useEncodeDataAttribute, | ||
QueryParams, | ||
UseQueryOptions, | ||
} from '@sanity/react-loader' | ||
const studioUrl = 'https://my.sanity.studio' | ||
const { | ||
// Used only server side | ||
loadQuery, | ||
setServerClient, | ||
// Used only client side | ||
useQuery: _useQuery, | ||
useLiveMode, | ||
} = createQueryStore({ client: false, ssr: true }) | ||
// Used only server side | ||
export { loadQuery, setServerClient } | ||
// Used only client side | ||
export { useLiveMode } | ||
export const useQuery = < | ||
QueryResponseResult = unknown, | ||
QueryResponseError = unknown, | ||
>( | ||
loadQuery: string, | ||
params?: QueryParams, | ||
options?: UseQueryOptions<QueryResponseResult>, | ||
) => { | ||
const snapshot = _useQuery<QueryResponseResult, QueryResponseError>( | ||
loadQuery, | ||
params, | ||
options, | ||
) | ||
const encodeDataAttribute = useEncodeDataAttribute( | ||
snapshot.data, | ||
snapshot.sourceMap, | ||
studioUrl, | ||
) | ||
return { | ||
...snapshot, | ||
encodeDataAttribute, | ||
} | ||
} | ||
``` | ||
You then use it in your template: | ||
```tsx | ||
// ./src/app/routes/products.$slug.tsx | ||
import { Link, useLoaderData, useParams } from '@remix-run/react' | ||
import { json, type LoaderFunction } from '@remix-run/node' | ||
import { loadQuery } from '~/sanity.loader.server' | ||
import { useQuery } from '~/sanity.loader' | ||
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, | ||
}) | ||
// Use `data` in your view, it'll mirror what the loader returns in production mode, | ||
// while Live Mode it becomes reactive and respons in real-time to your edits in the Presentation tool. | ||
// And `encodeDataAttribute` is a helpful utility for adding custom `data-sanity` attributes. | ||
return <ProductTemplate data={data} /> | ||
} | ||
``` | ||
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. | ||
```tsx | ||
// ./src/app/templates/product.tsx | ||
import { StudioPathLike } from '@sanity/react-loader' | ||
interface Product {} | ||
interface Props { | ||
data: Product | ||
encodeDataAttribute: (path: StudioPathLike) => string | undefined | ||
} | ||
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 | ||
/> | ||
</> | ||
) | ||
} | ||
``` | ||
## Visual Editing | ||
@@ -163,5 +287,1 @@ | ||
[bundlephobia]: https://bundlephobia.com/package/@sanity/react-loader@pink-lizard | ||
``` | ||
``` |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
374833
280