SimeonGriggs / sanity-react-router-template

Sanity Studio v3 embedded into a Remix Vite application configured for Vercel hosting with visual editing
https://sanity-remix-template.sanity.build
164 stars 35 forks source link

Error: `setServerClient` can only be called once when remix hot-reloads #53

Closed webprismdevin closed 10 months ago

webprismdevin commented 10 months ago

I'm following your template for our remix-based site (fresh install w/ npx create-remix@latest).

When in development, this error shows once a change is made and the site hot-reloads.

Any thoughts?

CleanShot 2024-01-11 at 18 42 00@2x

GET / 200 - - 112.041 ms
 info  rebuilding... (~ app/sanity-modules/PortableText.tsx)
 info  rebuilt (227ms)

/Users/devin/WEBPRISM/webprism/remix/node_modules/@sanity/core-loader/src/index.ts:249
      throw new Error('`setServerClient` can only be called once')
            ^
Error: `setServerClient` can only be called once
    at Module.setServerClient (/Users/devin/WEBPRISM/webprism/remix/node_modules/@sanity/core-loader/src/index.ts:249:13)
    at file:///Users/devin/WEBPRISM/webprism/remix/app/sanity/loader.server.ts:10:12
    at ModuleJob.run (node:internal/modules/esm/module_job:218:25)
    at ModuleLoader.import (node:internal/modules/esm/loader:329:24)
    at importModuleDynamicallyWrapper (node:internal/vm/module:430:15)
    at FSWatcher.handleServerUpdate (/Users/devin/WEBPRISM/webprism/remix/node_modules/@remix-run/serve/dist/cli.js:91:15)
webprismdevin commented 10 months ago

Okay, so figured this out by looking at your walkthrough article.

Here's how I solved it:

// ./app/sanity/loader.ts

import { createQueryStore } from "@sanity/react-loader";

// This is the "smallest" possible version of a query store
// Where stega-enabled queries only happen server-side to avoid bundle bloat
export const queryStore = createQueryStore({ client: false, ssr: true });

export const { useLiveMode, useQuery } = queryStore;
import { queryStore } from "~/sanity/loader";

import { client } from "~/sanity/client";

const clientWithToken = client.withConfig({
  token: process.env.SANITY_READ_TOKEN,
});

// We need to set the client used by `loadQuery` here, it only affects the server and ensures the browser bundle isn't bloated
queryStore.setServerClient(clientWithToken);

export const { loadQuery } = queryStore;

I was importing queryStore from '@sanity/react-loader' rather than from my loader.ts