【问题标题】:React Apollo Query/Mutation TypescriptReact Apollo 查询/突变打字稿
【发布时间】:2023-04-11 08:01:01
【问题描述】:

我需要帮助来尝试对突变和查询进行打字。文档和示例是有限的,我正在努力理解如何去做。我不太了解文档中的最后一个属性。它似乎是输入,响应,变量,?。 https://www.apollographql.com/docs/react/recipes/static-typing

在我必须使用 any 的地方进行查询和变异:

interface Data {
  loading: DataValue<boolean> | undefined;
  isLinkValid: DataValue<boolean> | undefined;
}
interface InputProps {
  location: {
    search: string;
  };
  showToast: Function;
}
interface Variables {
  id: string | string[] | null | undefined;
}

const validateLinkQuery = graphql<InputProps, Data, Variables, Data>(VALIDATE_LINK_MUTATION, {
  options: ({ location }) => {
    const params = QueryString.parse(location.search);
    const id = params.id;
    return {
      variables: { id },
    };
  },
  props: ({
    ownProps,
    data,
  }: {
    ownProps: {
      showToast: Function;
    };
    data?: any;
  }) => {
    const { validateLink, loading, error } = data;
    if (error) {
      ownProps.showToast(
        Type.ERROR,
        get(error, 'graphQLErrors[0].message', 'An error occured on the validate link query')
      );
    }
    return {
      isLinkValid: validateLink,
      loading,
    };
  },
});



const validateUserMutation = graphql(
  VALIDATE_CARD_MUTATION,
  {
    props: ({ ownProps, mutate }) => ({
      validateCard: (access: SubmitAccessInput) =>
        mutate({
          variables: {
            access,
          },
        })
          .then((response: any) => response)
          .catch((error: any) => {
            ownProps.showToast(
              Type.ERROR,
              get(error, 'graphQLErrors[0].message', 'An error occurred while signing up for an account')
            );
          }),
    }),
  }
);```

【问题讨论】:

  • 无法理解查询或突变的类型定义是什么意思。如果您需要在客户端进行突变和查询的类型定义。它们有很多方法。

标签: typescript react-apollo


【解决方案1】:

我会使用 https://github.com/dotansimha/graphql-code-generator 库,该库的生成器类型和 React Apollo HOC 组件的类型基于您的 graphql 模式。

在你可以做这样的事情之后。

import * as React from "react";
import { Mutation } from "react-apollo";
import { gql } from "apollo-boost";
import { RouteComponentProps } from "react-router-dom";

import { LoginMutationVariables, LoginMutation } from "../../schemaTypes";
import { meQuery } from "../../graphql/queries/me";
import { userFragment } from "../../graphql/fragments/userFragment";
import { Form } from "./Form";

const loginMutation = gql`
  mutation LoginMutation($email: String!, $password: String!) {
    login(email: $email, password: $password) {
      ...UserInfo
    }
  }

  ${userFragment}
`;

export class LoginView extends React.PureComponent<RouteComponentProps<{}>> {
  render() {
    return (
      <Mutation<LoginMutation, LoginMutationVariables>
        update={(cache, { data }) => {
          if (!data || !data.login) {
            return;
          }

          cache.writeQuery({
            query: meQuery,
            data: { me: data.login }
          });
        }}
        mutation={loginMutation}
      >
        {(mutate, { client }) => (
          <Form
            buttonText="login"
            onSubmit={async data => {
              // optional reset cache
              await client.resetStore();
              const response = await mutate({
                variables: data
              });
              console.log(response);
              this.props.history.push("/account");
            }}
          />
        )}
      </Mutation>
    );
  }
}

这里LoginMutationVariables和LoginMutation类型是通过graphql-code-generator生成的。

graphql-code-generator 还生成 `React Apollo Mutation/Query Hoc 组件,其类型适用于所有突变和查询。所以你甚至不需要传递这些类型。生成 HOC 组件后,你可以像这样编写相同的组件

<LoginMutationComponent>
... rest of the code
</LoginMutationComponent>

而不是这样做

<Mutation<LoginMutation, LoginMutationVariables>

但是你需要配置graphql-code-generator。如果你想为查询和变异生成 HOC 组件

【讨论】:

  • 谢谢你,如果我能正常工作,我会试一试,并用我的解决方案回复你。
  • 如果您对此有任何问题,请告知。所以我可以帮你
猜你喜欢
  • 2019-11-18
  • 1970-01-01
  • 2020-11-04
  • 2021-12-29
  • 1970-01-01
  • 2020-01-11
  • 2019-10-22
  • 2020-02-19
  • 2019-09-18
相关资源
最近更新 更多