我需要帮助尝试输入突变和查询的打字稿。该文档和示例是有限的,我正在努力设法了解如何做到这一点。我不太了解文档中的最后一个属性。它似乎是输入,响应,变量,?。 https://www.apollographql.com/docs/react/recipes/static-typing
在下面我必须使用的查询和变异:
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')
);
}),
}),
}
);```
答案 0 :(得分:0)
我将使用[https://github.com/dotansimha/graphql-code-generator][1]
库,该库的生成器类型和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>
);
}
}
在这里,通过graphql-code-generator生成LoginMutationVariables和LoginMutation类型。
graphql-code-generator
还会为所有突变和查询生成`React Apollo Mutation / Query Hoc组件,其类型为。因此,您甚至不需要传递这些类型。生成HOC组件后,您可以像这样编写相同的组件
<LoginMutationComponent>
... rest of the code
</LoginMutationComponent>
而不是像这样
<Mutation<LoginMutation, LoginMutationVariables>
但是您需要配置graphql-code-generator。如果要生成查询和变异的HOC组件