zoukankan      html  css  js  c++  java
  • [React] Update Application State with React Apollo ApolloConsumer Component

    In this lesson I refactor some code that utilizes the Mutation component to update client-side cache to use the new ApolloConsumer component baked into react-apollo 2.1.

    Additional Resources: https://dev-blog.apollodata.com/introducing-react-apollo-2-1-c837cc23d926

    If just working on local state, we can use ApolloConsumer:

    import React from "react";
    import { render } from "react-dom";
    
    import ApolloClient, { gql } from "apollo-boost";
    import {
      ApolloProvider,
      Query,
      Mutation,
      compose,
      graphql,
      ApolloConsumer
    } from "react-apollo";
    
    const defaults = {
      items: ["Apple", "Orange"]
    };
    
    const GET_ITEMS = gql`
      query {
        items @client
      }
    `;
    
    const client = new ApolloClient({
      clientState: {
        defaults
      }
    });
    
    const Items = () => (
      <Query query={GET_ITEMS}>
        {({ loading, error, data }) => {
          if (loading) return <p>Loading...</p>;
          if (error) return <p>Error :(</p>;
    
          return data.items.map(item => <div key={item}>{item}</div>);
        }}
      </Query>
    );
    
    const AddItem = ({ addItem }) => {
      let input;
      return (
        <ApolloConsumer>
          {cache => (
            <div>
              <form
                onSubmit={e => {
                  e.preventDefault();
                  let { items } = cache.readQuery({ query: GET_ITEMS });
                  items = [...items, input.value];
                  cache.writeData({ data: { items } });
                  input.value = "";
                  input.focus();
                }}
              >
                <input ref={node => (input = node)} />
                <button type="submit">Add Item</button>
              </form>
            </div>
          )}
        </ApolloConsumer>
      );
    };
    
    const App = () => (
      <div>
        <div>
          <Items />
          <AddItem />
        </div>
      </div>
    );
    
    const ApolloApp = () => (
      <ApolloProvider client={client}>
        <App />
      </ApolloProvider>
    );
    
    render(<ApolloApp />, document.getElementById("root"));

  • 相关阅读:
    u-boot启动流程分析(1)_平台相关部分
    Linux文件系统简介
    PHP将部分内容替换成星号
    自制jQuery焦点图切换简易插件
    一次解决页面特效问题的排查记录
    自制jQuery标签插件
    一套后台管理html模版
    自制jquery可编辑的下拉框
    注册页面的一些记录
    CSS选择器的一些记录
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9030830.html
Copyright © 2011-2022 走看看