码迷,mamicode.com
首页 > 其他好文 > 详细

[React + GraphQL] Use useLazyQuery to manually execute a query with Apollo React Hooks

时间:2019-08-29 20:29:12      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:red   color   isp   input   tar   str   val   with   null   

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, width: 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;

 

[React + GraphQL] Use useLazyQuery to manually execute a query with Apollo React Hooks

标签:red   color   isp   input   tar   str   val   with   null   

原文地址:https://www.cnblogs.com/Answer1215/p/11431567.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!