zoukankan      html  css  js  c++  java
  • [React + GraphQL] Use useLazyQuery to manually execute a query with Apollo React Hooks

    When using useQuery from Apollo React Hooks, the request will be sent automatically after the component has been mounted. This might not be the desired behaviour as we might want to send the request in response to user action (for instance, after a button click).

    In this lesson we're going to learn how to use useLazyQuery hook to execute a query manually in order to fetch dog pictures.

    import React, { Fragment, useState } from "react";
    import { gql } from "apollo-boost";
    import { useLazyQuery } from "@apollo/react-hooks";
    
    const GET_DOGGO = gql`
      query Dog($breed: String!) {
        dog(breed: $breed) {
          id
          displayImage
        }
      }
    `;
    
    const App = () => {
      const [breed, setBreed] = useState("dingo");
      const [getDog, { loading, data }] = useLazyQuery(GET_DOGGO);
    
      if (loading) {
        return <h2>Loading...</h2>;
      }
    
      return (
        <Fragment>
          {data && data.dog ? (
            <img
              alt="Cute Doggo"
              src={data.dog.displayImage}
              style={{ height: 500,  500 }}
            />
          ) : null}
          <input
            type="text"
            onChange={event => setBreed(event.target.value)}
            placeholder="Choose breed"
          />
          <button
            onClick={() =>
              getDog({
                variables: { breed }
              })
            }
          >
            Get dog
          </button>
        </Fragment>
      );
    };
    
    export default App;
  • 相关阅读:
    2013.11.18 流水
    return to blog!
    IOS实现毛玻璃效果的三种方式
    UI常用控件总结(三)
    UI常用控件总结(二)
    UI常用控件总结(一)
    UIView 常见属性
    OC语言BLOCK和协议
    OC语言类的深入和分类
    OC语言构造方法
  • 原文地址:https://www.cnblogs.com/Answer1215/p/11431567.html
Copyright © 2011-2022 走看看