码迷,mamicode.com
首页 > 其他好文 > 详细

[GraphQL] Apollo React Mutation Component

时间:2018-04-30 16:44:24      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:bak   cto   form   overflow   back   NPU   poll   prevent   color   

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

标签:bak   cto   form   overflow   back   NPU   poll   prevent   color   

原文地址:https://www.cnblogs.com/Answer1215/p/8973795.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!