urql是一个快速,轻巧且可自定义的GraphQL客户端。是一个js的库。
# npm
npm i --save urql graphql
# or yarn
yarn add urql graphql
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,error三个属性,分别代表数据结果,执行未完成和出错信息。
与查询不一样的是,变更语句不会在调用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.
});
};
};
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有