[GraphQL] Apollo React Mutation Component
2024-09-06 11:19:15
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>
);
};
最新文章
- domReady的实现
- bzoj 2434 阿狸的打字机 fail树的性质
- java位运算符介绍
- EntityFramework动态多条件查询与Lambda表达式树
- 大熊君大话NodeJS之开篇------Why NodeJS(将Javascript进行到底)
- [mysql] Some non-transactional changed tables couldn&#39;t be rolled back
- 关于Cookie和Session的优缺点
- jquery中对动态生成的标签响应click事件(二)…与ajax交互使用
- OPENCV3.1+VS 坑我笔记!
- 还在用GCD?来看看NSOperation吧
- K - Ignatius and the Princess IV
- 使用HTML5拍照
- H5学习之旅-H5列表(8)
- nyoj 633 幂
- Java的两大数据类型
- IntelliJ IDEA使用教程(简介)
- 保存canvas
- 函数和函数模版在一个。cpp中的情况!(除了左移和右移,其他的不要用友元函数!!!)
- 软件开发常用的linux命令心得
- 保护 iOS 用户数据安全: Keychain 和 Touch ID