[GraphQL] Apollo React Mutation Component
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[GraphQL] Apollo React Mutation Component相关的知识,希望对你有一定的参考价值。
In this lesson I refactor a React component that utilizes a higher-order component for mutations to the new Mutation render prop component baked into react-apollo 2.1.
Additional Resources: https://dev-blog.apollodata.com/introducing-react-apollo-2-1-c837cc23d926
If you want to mutate the server state, you can use <Mutation> component to simplify the code:
const ADD_ITEM = gql` mutation addItem($value: String!) { addItem(value: $value) @client } `; const client = new ApolloClient({ clientState: { defaults, resolvers: { Mutation: { addItem: (_, { value }, { cache }) => { let { items } = cache.readQuery({ query: GET_ITEMS }); items = [...items, value]; cache.writeData({ data: { items } }); return null; } } } } }); const AddItem = () => { let input; return ( <Mutation mutation={ADD_ITEM}> {(addItem, { loading, error, data }) => ( <div> <form onSubmit={e => { e.preventDefault(); addItem({ variables: { value: input.value } }); input.value = ""; input.focus(); }} > <input ref={node => (input = node)} /> <button type="submit">Add Item</button> </form> </div> )} </Mutation> ); };
以上是关于[GraphQL] Apollo React Mutation Component的主要内容,如果未能解决你的问题,请参考以下文章
GraphQL“必须提供查询字符串” graphql-tag react-apollo
React + Apollo:GraphQL 错误数组未传递到组件中