Unlock seamless workflows and faster delivery with our latest releases - Join the deep dive

How to get schema types into a TypeScript project with a React.js app and Sanity.io

11 replies
Last updated: Feb 3, 2023
Hi - so you guys have probably dealt with this a lot already - but my head is exploding by finding the best solution on following problem:
I got a react.js app with typescript and a brand new sanity project. How do i get my schema types into the TS Project
I tried creating types with the
JSON to TS vsc PluginI tried the sanity-codegen npm pkg in my sanity project but that only throws a bunch of errors.

Anyone got any ideas or solutions already?
Appreciate it
🙏
Jan 11, 2023, 8:06 PM
Jan 11, 2023, 8:12 PM
Jan 11, 2023, 8:12 PM
You do lose out on the power of GROQ queries, but automatic type/hook generation is too good to pass up.
Jan 11, 2023, 8:13 PM
Thanks - i've been tryna ditch GraphQL as long as possible, but I guess my time has also come now 🙂
Jan 11, 2023, 8:14 PM
user T
do you maybe have a public GitHub Repo as example?
Jan 11, 2023, 8:34 PM
Not a public one, no. Sorry.
Jan 11, 2023, 8:39 PM
codegen.ts
:

import type { CodegenConfig } from "@graphql-codegen/cli";

const config: CodegenConfig = {
  overwrite: true,
  schema: "<https://YOUR_PROJECT_ID_HERE.api.sanity.io/v1/graphql/production/default>",
  ignoreNoDocuments: true,
  documents: ["./src/graphql/**/*.{graphql,ts}"],
  generates: {
    "./src/services/index.ts": {
      plugins: [
        "typescript",
        "typescript-operations",
        "typescript-react-query",
      ],
      config: {
        fetcher: "../lib/fetcher#fetchData",
        exposeDocument: true,
        exposeQueryKeys: true,
        exposeMutationKeys: true,
        exposeFetcher: true,
        strictScalars: true,
        scalars: {
          Date: "string",
          DateTime: "string",
          JSON: "{ [key: string]: any }",
        },
      },
    },
  },
};

export default config;
Jan 11, 2023, 8:49 PM
Example graphql query:

import { gql } from "@apollo/client";

export const GET_ALL_ARTICLES = gql`
  query getAllArticles {
    allArticle(where: { _: { is_draft: false } }) {
      _id
      slug {
        current
      }
    }
  }
`;
Jan 11, 2023, 8:50 PM
lib/fetcher/index.ts
:
export const fetchData = &lt;TData, TVariables&gt;(
_query_: string,

variables?: TVariables,
options?: RequestInit[“headers”]): (() =&gt; Promise&lt;TData&gt;) =&gt; {
return async () =&gt; {
const RESPONSE = await fetch(process.env.NEXT_PUBLIC_SANITY_GRAPHQL_URL, {
method: “POST”,
headers: {
Authorization:
Bearer ${process.env.NEXT_PUBLIC_SANITY_TOKEN}
, “Content-Type”: “application/json”,
...
options, },
body: JSON.stringify({
query,
variables,
}),
});

const JSON_RESPONSE = await RESPONSE.json();

if (JSON_RESPONSE.errors) {
const { message } = JSON_RESPONSE.errors[0] || {};
throw new Error(message || “Error...“);
}

return JSON_RESPONSE.data;
};
};
Jan 11, 2023, 8:51 PM
user T
thank you so much 🙏 Will try it out! Since i got 0xp with GraphQL I'm gonna start with some tutorials on that topic first
Jan 11, 2023, 8:52 PM
user T
, seems like you’re exposing the sanity token client side, should you do that?
Feb 3, 2023, 12:12 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?