[React] Update Application State with React Apollo ApolloConsumer Component

本文介绍如何利用react-apollo 2.1中的ApolloConsumer组件来更新客户端缓存,替代Mutation组件,并通过示例代码展示了如何实现对本地状态的读取与修改。

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"));

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值