[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"));
复制代码

 

posted @   Zhentiw  阅读(385)  评论(0编辑  收藏  举报
编辑推荐:
· 智能桌面机器人:用.NET IoT库控制舵机并多方法播放表情
· Linux glibc自带哈希表的用例及性能测试
· 深入理解 Mybatis 分库分表执行原理
· 如何打造一个高并发系统?
· .NET Core GC压缩(compact_phase)底层原理浅谈
阅读排行:
· 新年开篇:在本地部署DeepSeek大模型实现联网增强的AI应用
· DeepSeek火爆全网,官网宕机?本地部署一个随便玩「LLM探索」
· Janus Pro:DeepSeek 开源革新,多模态 AI 的未来
· 上周热点回顾(1.20-1.26)
· 【译】.NET 升级助手现在支持升级到集中式包管理
历史上的今天:
2016-05-13 [Javascript] Writing conventional commits with commitizen
2016-05-13 [Javascript] Automating Releases with semantic-release
2015-05-13 [Whole Web] [Node.js, PM2] Controlling runaway apps using pm2
2015-05-13 [AngularJS] angular-formly: Default Options
点击右上角即可分享
微信分享提示