美文网首页
Graphql mutation

Graphql mutation

作者: NOTEBOOK2 | 来源:发表于2018-05-03 16:58 被阅读0次

更新缓存,处理错误

The Mutation component

首先创建GraphQL mutation
第一个参数:variables、optimisticResponse、refetchQueries、update
第二个参数:对象

import gql from "graphql-tag";
import { Mutation } from "react-apollo";

const ADD_TODO = gql`
  mutation addTodo($type: String!) {
    addTodo(type: $type) {
      id
      type
    }
  }
`;

const AddTodo = () => {
  let input;

  return (
    <Mutation mutation={ADD_TODO}>
      {(addTodo, { data }) => (
        <div>
          <form
            onSubmit={e => {
              e.preventDefault();
              addTodo({ variables: { type: input.value } });
              input.value = "";
            }}
          >
            <input
              ref={node => {
                input = node;
              }}
            />
            <button type="submit">Add Todo</button>
          </form>
        </div>
      )}
    </Mutation>
  );
};  

Updating the cache

第一个参数 update方法

cache.readQuery  
cache.writeQuery  
cache.readFragment   
cache.writeFragment  
cache.writeData  

第二个参数 对象

const AddTodo = () => {
  let input;

  return (
    <Mutation
      mutation={ADD_TODO}
      update={(cache, { data: { addTodo } }) => {
        const { todos } = cache.readQuery({ query: GET_TODOS });
        cache.writeQuery({
          query: GET_TODOS,
          data: { todos: todos.concat([addTodo]) }
        });
      }}
    >
      {addTodo => (
        <div>
          <form
            onSubmit={e => {
              e.preventDefault();
              addTodo({ variables: { type: input.value } });
              input.value = "";
            }}
          >
            <input
              ref={node => {
                input = node;
              }}
            />
            <button type="submit">Add Todo</button>
          </form>
        </div>
      )}
    </Mutation>
  );
};   

相关文章

网友评论

      本文标题:Graphql mutation

      本文链接:https://www.haomeiwen.com/subject/fttlrftx.html