[React] Update Application State with React Apollo ApolloConsumer Component

时间:2021-10-22 10:35:55

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