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> ); };
原文地址:https://www.cnblogs.com/Answer1215/p/8973795.html
时间: 2024-10-31 09:27:21