使用urql实现GraphQL客户端
程序员文章站
2022-05-16 10:35:50
...
urql简介
urql是一个快速,轻巧且可自定义的GraphQL客户端。是一个js的库。
安装urql
# npm
npm i --save urql graphql
# or yarn
yarn add urql graphql
使用urql
- 从服务器 GraphQL Endpoint 来生成客户端
import { createClient, Provider } from 'urql';
const client = createClient({
url: 'https://0ufyz.sse.codesandbox.io' ,
fetchOptions: () => {
const token = getToken();
return {
headers: { authorization: token ? `Bearer ${token}` : '' }
};
}
});
const App = () => (
<Provider value={client}>
<Todos />
</Provider>
);
通过createClient创建一个客户端,url指定服务端地址,fetchOptions提供一个函数,返回要添加到请求中的参数信息,比如token
利用react的上下文来传递客户端给子组件,则接下来在Todos组件中可以直接使用query而不需要再次创建客户端
- 执行查询
import { useQuery } from 'urql';
const TodosQuery = `
query ($id : ID!) {
todos {
id
title
}
}
`;
const Todos = () => {
const [result, reexecuteQuery] = useQuery({
query: TodosQuery,
variables: {"id" : '1111' }
});
const { data, fetching, error } = result;
if (fetching) return <p>Loading...</p>;
if (error) return <p>Oh no... {error.message}</p>;
return (
<ul>
{data.todos.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
);
};
通过useQuery这个Hook函数,即刻进行查询返回结果,其中query参数代表请求的GraphQL语句,variables参数代表传递的变量数据。
返回值是数组,第一个值是结果,结果包含data,fetching,erro桑属性,分别代表数据结果,执行未完成和出错信息。
- 执行变更
与查询不一样的是,变更语句不会在调用useMutation这个Hook函数时立即执行,而是需要通过函数返回值的第二个元素(其是一个函数),传入数据调用以后才会请求执行。
import { useMutation} from 'urql';
const UpdateTodo = `
mutation ($id: ID!, $title: String!) {
updateTodo (id: $id, title: $title) {
id
title
}
}
`;
const Todo = ({ id, title }) => {
const [updateTodoResult, updateTodo] = useMutation(UpdateTodo);
const submit = newTitle => {
const variables = { id, title: newTitle || '' };
updateTodo(variables).then(result => {
// The result is almost identical to `updateTodoResult` with the exception
// of `result.fetching` not being set.
});
};
};
推荐阅读
-
php识别微信客户端并且使用html静态页面引导用户使用浏览器打开这个页面(代码实现教程)
-
Android开发使用json实现服务器与客户端数据的交互功能示例
-
C#使用Socket实现服务器与多个客户端通信(简单的聊天系统)
-
Python使用ftplib实现简易FTP客户端的方法
-
在代码生成工具Database2Sharp中使用ODP.NET(Oracle.ManagedDataAccess.dll)访问Oracle数据库,实现免安装Oracle客户端,兼容32位64位Oracle驱动
-
Java开发之使用websocket实现web客户端与服务器之间的实时通讯
-
豆瓣电台WP7客户端 MVVM重构记录之使用MVVM Light实现Event绑定
-
PHP实现检测客户端是否使用代理服务器及其匿名级别
-
asp.net Core 使用过滤器判断请求客户端是否为移动端,并实现PC端和移动端请求映射和自动跳转
-
C#使用Socket实现服务器与多个客户端通信(简单的聊天系统)