urql的简单使用

1.urql的安装

# npm
npm i --save urql graphql
# or yarn
yarn add urql graphql

2.创建客户端

import { createClient, Provider } from 'urql';
const client = createClient({ url: 'https://0ufyz.sse.codesandbox.io' });
const App = () => (
  <Provider value={client}>
    <Todos />
  </Provider>
);

分析:Provider是React中的context上下文,用于在上下级组件中共享数据,在这里是将创建的客户端共享给子组件Todos

3.查询语句

const Todos = () => {
  const [res, executeQuery] = useQuery({
    query: `
      query { todos { id text } }
    `,
  });
  if (res.fetching) return <p>Loading...</p>;
  if (res.error) return <p>Errored!</p>;
  return (
    <ul>
      {res.data.todos.map(todo => (
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
};

分析:使用urql提供的useQuery进行数据查询,useQuery有两个参数,第一个是GraphQL语句,第二个是variables参数,用于条件查询,返回的res是一个JSON对象,分别包含data--结果数据、fetching--是否正在加载数据、error--错误结果

4.变更语句

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 => {
      if (result.error) {
        console.error('Oh no!', result.error);
      }
    });
  };
};

分析:大致与查询语句类似,不一样的是,如果要执行变更,需要对第二个参数updateTodo进行传入参数variables

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值