【问题标题】:How to type a mutation in typescript + apollo如何在 typescript + apollo 中输入突变
【发布时间】:2018-09-01 09:10:36
【问题描述】:

鉴于我有一个看起来像这样的突变。

mutation SignInMutation($email: String!, $password: String!) {
  signIn(input: {email: $email, password: $password}) {
    token {
      accessToken
      accessTokenExpiresOn
    }
  }
}

如何使用react-apollo 中的graphql 函数类型然后将signIn 方法添加到类?

例如

import SignInMutation from '~/mutations/SignInMutation.gql`
import { graphql } from 'react-apollo'

@graphql(SignInMutation, {
  props: ({ mutate }) => ({
    signIn: (variables) => mutate({variables})
  })
})
class SignInPage extends React.Component {
  state = {
    email: '',
    password: '',
  }
  render() {
   <form>
     ...
     <button onClick={() => this.props.signIn(this.state)}>
     </button>
   </form>
  }
}

【问题讨论】:

  • 我不确定我是否理解清楚,但请尝试 @graphql(SignInMutation, {name: 'signIn'}) 然后您可以使用 SignInMutation 作为道具中的登录方法。在类中定义例如。 handleSignIn 并使用适当的变量调用 this.props.signIn。或者您可能想避免创建 handleSignIn 方法?
  • @magnat,执行我所做的实现或您建议的实现都会导致装饰器输入不正确。我收到一条错误消息,提示 Unable to resolve signature of class decorator when called as an expression. Type 'ComponentClass&lt;SignInProps&gt;' is not assignable to type 'typeof SignInPage'. Type 'Component&lt;SignInProps, ComponentState&gt;' is not assignable to type 'SignInPage'. Property 'handleSubmit' is missing in type 'Component&lt;SignInProps, ComponentState&gt;'.

标签: typescript apollo react-apollo


【解决方案1】:

有一个小型库和一个 CLI,可以使用项目中 GraphQL 文件中的查询和突变来生成 react-apollo 组件。因此,您可以通过导入生成的文件来轻松使用它们;

import { YourQuery } from './generated';

<YourQuery.Component>
...
</YourQuery.Component>

你可以在这里试试:https://github.com/dotansimha/graphql-code-generator

这里有一篇博文; https://medium.com/the-guild/graphql-code-generator-for-typescript-react-apollo-7b225672588f

【讨论】:

    猜你喜欢
    • 2020-05-29
    • 2019-11-11
    • 2020-05-18
    • 2021-11-05
    • 2019-08-09
    • 2016-03-30
    • 2018-03-17
    • 2019-11-28
    • 2018-08-11
    相关资源
    最近更新 更多