【问题标题】:How can I repeatedly call my graphql query?如何重复调用我的 graphql 查询?
【发布时间】:2022-01-16 22:38:34
【问题描述】:

我正在尝试实现 graphql。我将我的 graphql 查询放在一个函数 FetchProducts() 中,因为我想重复调用这个函数。函数如下所示:

const Products = () => {
  let productsFilters;
  let products;

  const { category } = useParams();

  productsFilters = new ProductsFilters();
  productsFilters.setSpecificCategory(category);

  useEffect(() => {
    FetchProducts();
  }, [])



  const FetchProducts = () => {
    const queryParams = buildQueryParams(productsFilters);

    const { loading, data } = useQuery(FETCH_PRODUCTS_QUERY, {
      variables: {
        queryParams,
      },
    });

   products = data?.getProducts;
  }

 const handleChange = (item) => {
     item.checked = !item.checked;
    FetchProducts(productsFilters);
  };

 return (...)

我收到以下错误:

Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function 
component. This could happen for one of the following reasons:
 1. You might have mismatching versions of React and the renderer (such as React DOM)
 2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this 
problem.
    at 

【问题讨论】:

标签: reactjs graphql


【解决方案1】:

您可以使用useLazyQuery,而不是使用useQuery

import { useLazyQuery } from "@apollo/client"

const Products = () => {
  let productsFilters;
  let products;

  const { category } = useParams();
  const [fetchProductQuery, {loading, data }] = useLazyQuery(FETCH_PRODUCTS_QUERY);

  productsFilters = new ProductsFilters();
  productsFilters.setSpecificCategory(category);

  useEffect(() => {
    FetchProducts();
  }, [])



  const FetchProducts = () => {
    const queryParams = buildQueryParams(productsFilters);

    // const { loading, data } = useQuery(FETCH_PRODUCTS_QUERY, {
    //   variables: {
    //     queryParams,
    //   },
    // });

    fetchProductQuery({
      variables:{
        queryParams
      }
    })

   products = data?.getProducts;
  }

 const handleChange = (item) => {
     item.checked = !item.checked;
    FetchProducts(productsFilters);
  };

 return (...)

useLazyQuery索引0返回触发API调用的函数,索引1useQuery返回值相同。

【讨论】:

猜你喜欢
  • 2020-12-25
  • 2018-02-07
  • 2019-02-20
  • 2018-02-10
  • 2019-07-05
  • 1970-01-01
  • 2018-11-15
  • 2019-02-20
  • 1970-01-01
相关资源
最近更新 更多