The problem with the "typescript-react-apollo" codegen plugin is that it is declaring block-scope variables more than once in the generated

Recently, I embarked on a new project utilizing NextJS with graphql-codegen to auto-generate my apollo-react types from the API. Unfortunately, it seems to be generating duplicate exported variables right from the start, causing a typescript error and hindering the project build process. Any suggestions on how to prevent these duplicates while using codegen?

codegen.ts

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

const config: CodegenConfig = {
  overwrite: true,
  documents: ["src/**/*.tsx"],
  schema: process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT,
  generates: {
    "./src/graphql/__generated__/": {
      preset: "client",
      plugins: ["typescript-react-apollo"],
    },
  },
};
export default config;

codegen error

// ./src/graphql/__generated__/
...
// creates two 'UserDocument' variables
export const UserDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"User"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"userId"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"ObjectId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"userId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"image"}},{"kind":"Field","name":{"kind":"Name","value":"hashedPassword"}},{"kind":"Field","name":{"kind":"Name","value":"role"}}]}}]}}]} as unknown as DocumentNode<UserQuery, UserQueryVariables>;

export const UserDocument = gql`
    query User($userId: ObjectId) {
  user(id: $userId) {
    id
    name
    email
    image
    hashedPassword
    role
  }
}
    `;
...

Answer №1

I made the decision to remove the generates: { preset: 'client' } configuration and instead customized my own plugins and updated the settings:

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

const config: CodegenConfig = {
  overwrite: true,
  documents: ["src/**/*.tsx"],
  schema: process.env.NEXT_PUBLIC_GRAPHQL_ENDPOINT,
  generates: {
    "./src/graphql/__generated__/graphql.ts": {
      plugins: [
        "typescript",
        "typescript-operations",
        "typescript-react-apollo",
      ],
    },
  },
};
export default config;

This approach appears to be effective.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The loading of Google fonts becomes quite bizarre once the deployment to Vercel is complete

Recently, I deployed a Next.js app to the server using Vercel and referenced two Google fonts in the _document.js file. Surprisingly, while running the app locally, both fonts load without any issue. import Document, { Html, Head, Main, NextScript } from & ...

Dynamic importing fails to locate file without .js extension

I created a small TS app recently. Inside the project, there is a file named en.js with the following content: export default { name: "test" } However, when I attempt to import it, the import does not work as expected: await import("./e ...

Encountering a 4mb limit error while fetching/streaming a file URL using NextJS

Despite increasing the limit size in the API config at https://nextjs.org/docs/api-routes/api-middlewares#custom-config, I am still encountering a 4mb limit error while trying to fetch/stream a file URL. It seems that this issue remains unresolved as GitHu ...

How can I iterate through a directory containing files and extract the exported JavaScript object from each one?

In my current project using nodejs / nextjs, I have file system access and a folder containing multiple React files: content - blog-post-1.jsx - blog-post-2.jsx - blog-post-3.jsx The task at hand is to extract the frontmatter from each file. My init ...

When refreshing the page, redux-persist clears the state

I have integrated redux-persist into my Next.js project. The issue I am facing is that the state is getting saved in localStorage when the store is updated, but it gets reset every time the page changes. I suspect the problem lies within one of the reducer ...

The specified type does not meet the constraint as it lacks the required index signature

I'm currently working on refactoring a TypeScript project that utilizes React Hooks. While I have some knowledge of TypeScript, I am still more of a beginner than an expert. My main goal is to create reusable code for this project through the use of ...

Looking to utilize Axios in React to make API calls based on different categories upon clicking - how can I achieve this?

My current issue involves making an API call upon clicking, but all I see in my console is null. My goal is to have different API categories called depending on which item is clicked. const [category, setCategory] = useState(""); useEffect(() => { ...

Error: Attempting to access property 'error' of an undefined object resulted in an unhandled exception

I encountered an error when using the handleSubmit function in the Register component: Uncaught (in promise) TypeError: Cannot read property 'error' of undefined. Below, you can see the code for the component, how I fetch API data, and the Next. ...

NextJS 12: The dilemma of styled components not rendering server side due to missing CSS

Exciting news with the latest NextJS 12 release - now styled-components is supported without the need for any extra plugins on NextJS! However, I'm running into issues getting it to work with server-side rendering. To activate it, I installed the sty ...

Angular Error: Potential security risk detected in resource URL context due to unsafe value being used

Hey there, I'm looking to display a dynamic pdf file. Initially, I encountered a CORS error, but managed to resolve it by using DOM Sanitizer. However, now I'm facing an issue with unsafe URLs. Any assistance would be greatly appreciated. Below ...

The reasons behind cancellations in API requests

Within the parent component, the open and setOpen states were passed down to the child component. The fetchData function included open as a dependency in the useEffect hook. In the child component, open was also added as a dependency for another fetchDat ...

"Why does my Next.js page appear as 'not found' on Netlify after deployment, despite the rest of the layout

Upon deploying my project to Netlify, I encountered an unusual issue where only the root layout with the header was being displayed. You can find my project repository here: https://github.com/Kiritsu0/Facebook-Clone Here is the link to my Netlify pr ...

Is there a method to retrieve the bounds (northeast and southwest) of the map display when there is a change in the bounds, center, or view area?

In my NextJs project, I am utilizing the TomTom Map SDK to implement a feature where, upon loading the map based on its bounds, I query for nearby restaurants in that specific area. Additionally, when there are zoom or drag events on the map, I want to mak ...

What is the level of visibility in Nextjs?

Is it safe to expose the sources of files located in the 'pages/' directory? For instance, if you set up a page specifically for administrators at pages/admin and restrict access through Middleware, does this enhance security measures? ...

RC7 is missing the necessary HTTP_PROVIDERS for the resolveAndCreate HTTP method in Angular2

During the time of RC4, I was able to create my own custom http instance using a function like this: export function createHTTP(url:string, headers?:Headers){ let injector = ReflectiveInjector.resolveAndCreate([ myHttp, {provide:'defaultUrl ...

Passing data using the router.push method in 'next/navigation' is a quick and efficient way to transfer information between

Is there a way to pass data between routes using the router.push method in the useRouter() API from next/navigation? Additionally, are there any techniques for performing URL masking in the router.push method from next/navigation like we could do with nex ...

Retrieve the previous route in Angular 7

I have developed a unique service that allows me to store route changes efficiently. import { Injectable } from '@angular/core'; import { Router, NavigationEnd } from '@angular/router'; @Injectable() export class RouteState { priva ...

Executing vitest on compiled javascript files

Currently facing issues running vitest on compiled JavaScript. Numerous errors are appearing, such as: TypeError: Cannot read properties of undefined (reading 'spyOn') TypeError: Cannot read properties of undefined (reading 'mock') and ...

How can you loop through an array of objects in TypeScript without relying on the traditional forEach

Currently, I'm working on an array of objects with the following structure. [ { "matListParent": "CH", "dParent": "CUST1", "isAllSelected": true, "childItems&qu ...

Forgetting Passwords: utilizing Next.js with Strapi for password recovery

My current challenge involves sending a reset password email to the user's provided email in the forgot password form. However, when I attempt to do so, I encounter an "Internal Server Error" message... Below is the function that triggers upon submit ...