使用urql实现GraphQL客户端

使用urql实现GraphQL客户端

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.
    });
  };
};

欢迎找歪歪梯聊骚

原创文章 53 获赞 12 访问量 9136

猜你喜欢

转载自blog.csdn.net/weixin_44627989/article/details/105825411