简体   繁体   English

React Apollo查询/变异打字稿

[英]React Apollo Query/Mutation Typescript

I need help trying to typescript a mutation and Query. 我需要帮助尝试为突变和查询打字稿。 The documentation and examples are limited and i'm struggling to manage to understand how to do it. 该文档和示例是有限的,我正在努力设法了解如何做到这一点。 I don't really understand the last property from the documentation. 我不太了解文档中的最后一个属性。 It seems to be input, response, variables, ?. 它似乎是输入,响应,变量,?。 https://www.apollographql.com/docs/react/recipes/static-typing https://www.apollographql.com/docs/react/recipes/static-typing

query and mutation below where I had to use 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')
            );
          }),
    }),
  }
);```

I would use https://github.com/dotansimha/graphql-code-generator library which generator type and React Apollo HOC component with type based on your graphql schema. 我会使用https://github.com/dotansimha/graphql-code-generator库,该库基于您的graphql模式生成器类型和具有类型的React Apollo HOC组件。

After you can do something like this. 之后,您可以执行以下操作。

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>
    );
  }
}

Here LoginMutationVariables and LoginMutation type are being generated through graphql-code-generator. 这里,通过graphql-code-generator生成LoginMutationVariables和LoginMutation类型。

graphql-code-generator also generate `React Apollo Mutation/Query Hoc component with type for all mutation and queries. graphql-code-generator还会为所有变异和查询生成`React Apollo Mutation / Query Hoc组件,其类型为。 So you don't even need to pass these type. 因此,您甚至不需要传递这些类型。 After generating HOC component, you can write same component like this 生成HOC组件后,您可以像这样编写相同的组件

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

rather than doing like this 而不是像这样

<Mutation<LoginMutation, LoginMutationVariables>

But you need to configure graphql-code-generator. 但是您需要配置graphql-code-generator。 if you want to generate HOC component for queries and mutation 如果要生成用于查询和变异的HOC组件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM