[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"));
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 智能桌面机器人:用.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