Applo React Hooks-CheatsheetReact, React Hooks

Applo React Hooks-Cheatsheet

@apollo/react-hooks

实现客户端通过 hooks 调用 gql 的库

useQuery

import {useQuery} from '@apollo/react-hooks';
import gql from 'graphql-tag';

const GET_GREETING = gql`
  query getGreeting($language: String!) {
    greeting(language: $language) {
      message
    }
  }
`;

function Hello() {
  // 直接返回一个 Obj
  // 对于 Query, 直接在 FC 里面调用即可
  const {loading, error, data} = useQuery(GET_GREETING, {
    variables: {language: 'english'},
  });
  if (loading) return <p>Loading ...</p>;
  return <h1>Hello {data.greeting.message}!</h1>;
}

useMutation

import {useMutation} from '@apollo/react-hooks';
import gql from 'graphql-tag';

const ADD_TODO = gql`
  mutation AddTodo($type: String!) {
    addTodo(type: $type) {
      id
      type
    }
  }
`;

function AddTodo() {
  let input;
  // 直接返回一个数组
  // 对于 mutation, 首先要获取到实际的 setStateAction, 需要注意的是这个地方 setStateAction 是返回数组的第一个参数
  // 和 setState 返回的顺序不同
  const [addTodo, { data}] = useMutation(ADD_TODO);

  return (
    <div>
      <form
        onSubmit={e => {
          e.preventDefault();
          // 然后下方实际调用这个 mutation
          addTodo({variables: { type: input.value} });
          input.value = '';
        }}
      >
        <input
          ref={node => {
            input = node;
          }}
        />
        <button type="submit">Add Todo</button>
      </form>
    </div>
  );
}
Powered by Remix
|
Designed by szhshp
|
Copyright © szhshp 2022