Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to type a mutation in typescript + apollo

given I have a mutation that looks like this.

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

how would I use the type the graphql function in react-apollo to then add a signIn method to a class?

e.g.

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>
  }
}
like image 442
lifeiscontent Avatar asked Mar 22 '18 19:03

lifeiscontent


People also ask

What is mutation in Apollo Client?

Mutations are GraphQL operations that modify back-end data. As a convention in GraphQL, queries are read operations and mutations are write operations.

How do you call a mutation in React?

For mutations, the graphql HOC passes down a mutate prop, which we'll call to execute the mutation. import React from 'react'; import { gql, graphql } from 'react-apollo';const AddChannel = ({ mutate }) => { const handleKeyUp = (evt) => { if (evt. keyCode === 13) { evt. persist(); mutate({ variables: { name: evt.


1 Answers

There is a small library and a CLI to generate react-apollo components using your queries and mutations inside GraphQL files in your project. So, you can use them easily by importing generated file like;

import { YourQuery } from './generated';

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

You can try it here: https://github.com/dotansimha/graphql-code-generator

And there is a blog post here; https://medium.com/the-guild/graphql-code-generator-for-typescript-react-apollo-7b225672588f

like image 52
ardatan Avatar answered Oct 12 '22 01:10

ardatan