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

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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, 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的主要内容,如果未能解决你的问题,请参考以下文章

[GraphQL] Use GraphQLList with GraphQLObject Types

GraphQL 中的图像上传

[React] Use the new React Context API

React Hooks: use modal

[React] Use a Render Porp

React Hooks-useMemo篇