Apollo useMutation 添加数据,改变数据

useMutation 修改后台数据,并且更新前端视图
修改了数据之后,Apollo 会根据ID自动更新视图,所以修改数据不需要手动改变本地缓存,删除,或者添加数据需要修改本地缓存或者改变了多个数据也需要修改本地缓存

import React from "react";
import { render } from "react-dom";

import { ApolloClient } from "apollo-client";
import { ApolloProvider, useQuery, useMutation } from "@apollo/react-hooks";
import { HttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";
import gql from "graphql-tag";

const client = new ApolloClient({
  link: new HttpLink({
    uri: "https://plp0mopxq.sse.codesandbox.io/"
  }),
  cache: new InMemoryCache()
});

const GET_TODOS = gql`
  {
    todos {
      id
      type
    }
  }
`;

const UPDATE_TODO = gql`
  mutation UpdateTodo($id: String!, $type: String!) {
    updateTodo(id: $id, type: $type) {
      id
      type
    }
  }
`;

function Todos() {
  const { loading, error, data } = useQuery(GET_TODOS);

//    updateTodo自定义方法名,调用此方法执行这条查询
// 还返回一个对象 里面包括查询中的状态,数据等
  const [
    updateTodo,
    { loading: mutationLoading, error: mutationError,data:mutationData }
  ] = useMutation(UPDATE_TODO);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;

  return data.todos.map(({ id, type }) => {
    let input;

    return (
      <div key={id}>
        <p>{type}</p>
        <form
          onSubmit={e => {
            e.preventDefault();
            updateTodo({ variables: { id, type: input.value } });

            input.value = "";
          }}
        >
          <input
            ref={node => {
              input = node;
            }}
          />
          <button type="submit">Update Todo</button>
        </form>
        {mutationLoading && <p>Loading...</p>}
        {mutationError && <p>Error :( Please try again</p>}
      </div>
    );
  });
}

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

const TODOS = gql`
  {
    todos {
      id
    }
  }
`;

function AddTodo() {
  let input;
  // useMutation 接收第二个参数对象,改变本地缓存以更新视图
  const [addTodo] = useMutation(ADD_TODO, {
    //  update 发生突变后用于更新缓存的功能
    update(
      cache,
      {
      // 增加,删除,或者修改的数据
        data: { addTodo }
      }
    ) {
    // 读取本地缓存
      const { todos } = client.readQuery({ query: TODOS });
      // 写入缓存
      client.writeQuery({
        query: TODOS,
        // 将 增加,删除,或者修改的数据和本地数据进行合并 concat  删除使用 split
        data: { todos: todos.concat([addTodo]) }
      });
    }
  });

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

const App = () => (
  <ApolloProvider client={client}>
    <div>
      <h2>Building Mutation components 🚀</h2>
      <AddTodo />
      <Todos />
    </div>
  </ApolloProvider>
);

render(<App />, document.getElementById("root"));
发布了19 篇原创文章 · 获赞 1 · 访问量 516
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 游动-白 设计师: 上身试试

分享到微信朋友圈

×

扫一扫,手机浏览