redux rtk-query-graphql-request和graphql-request的类型不匹配

9wbgstp7  于 2022-11-24  发布在  其他
关注(0)|答案(2)|浏览(114)

我试图用GraphQL构建rtk查询API,但是@rtk-query/graphql-request-base-querygraphql-request之间的包类型不匹配,我得到如下错误;

Type 'import("path/to/file/node_modules/graphql-request/dist/index").GraphQLClient' is not assignable to type 'import("path/to/file/node_modules/@rtk-query/graphql-request-base-query/node_modules/graphql-request/dist/index").GraphQLClient'.
  Types have separate declarations of a private property 'url'.ts(2322)

我在graphqlRequestBaseQuery**client**字段上得到错误,我试图删除node_modules并重新安装,不幸的是没有工作...
这是我的api.ts

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
import { graphqlRequestBaseQuery } from '@rtk-query/graphql-request-base-query'; 
import { GraphQLClient } from 'graphql-request';
import { gqlClient } from '../gql/gql-client';

 
export const api = createApi({
  baseQuery: graphqlRequestBaseQuery({ client: new GraphQLClient('http://localhost:4000/graphql') }), // error is at "client" field
  tagTypes: [],
  endpoints: (builder) => ({
    getUsers: builder.query({
      query: () => '/users',
    }),
  }),
});

export const { useGetUsersQuery } = api;
af7jpaap

af7jpaap1#

下面是一个使用@rtk-query/graphql-request-base-query版本2.2.0的示例。

import { createApi } from "@reduxjs/toolkit/query/react";
import { graphqlRequestBaseQuery } from "@rtk-query/graphql-request-base-query";
import { ClientError } from "graphql-request";

import { RootState } from "../store";

const baseUrl = process.env.REACT_APP_TECHNOTES_API_HTTP_GRAPHQL;
const techNotesHttpAPI = baseUrl ? baseUrl : "http://localhost:4001/graphql";

const baseQuery = graphqlRequestBaseQuery<
  Partial<ClientError> & { statusCode: number; error: string }
>({
  url: techNotesHttpAPI,
  prepareHeaders: (headers, { getState }) => {
    const state = getState() as RootState;
    const token = state.auth.token;

    if (token) {
      headers.set("Authorization", `Bearer ${token}`);
    }

    return headers;
  },
  customErrors: ({ name, stack, response }) => {
    const {
      message = "",
      statusCode = 500,
      error = "",
    } = response?.errors?.length
      ? response?.errors[0]?.extensions.response
      : {};

    return {
      name,
      message,
      statusCode,
      error,
      stack,
    };
  },
});

export const apiSlice = createApi({
  reducerPath: "api",
  baseQuery,
  tagTypes: ["User", "Note"],
  endpoints: () => ({}),
});
l2osamch

l2osamch2#

我在遵循代码生成文档时遇到了同样的问题。要添加到@dwight建议的内容中,您也可以复制@rtk-query/graphql-request-base-query包的代码文件并将它们放入您的项目中。从那里导入graphqlRequestBaseQuery
@rtk-query/graphql-request-base-query在内部从graphql-request导入GraphQLClient,类型不匹配可能是因为尚未在正式存储库中更新相关性。
我希望这能有所帮助

相关问题