[React] Update Application State with React Apollo ApolloConsume
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"));
相关推荐
游走的豚鼠君 2020-11-10
81417707 2020-10-30
ctg 2020-10-14
小飞侠V 2020-09-25
PncLogon 2020-09-24
jipengx 2020-09-10
颤抖吧腿子 2020-09-04
wwzaqw 2020-09-04
maple00 2020-09-02
青蓝 2020-08-26
罗忠浩 2020-08-16
liduote 2020-08-13
不知道该写啥QAQ 2020-08-02
pengruiyu 2020-08-01
wmd看海 2020-07-27
孝平 2020-07-18
Eduenth 2020-07-05
iftrueIloveit 2020-07-04