jaydenseric / graphql-react

A GraphQL client for React using modern context and hooks APIs that is lightweight (< 4 kB) but powerful; the first Relay and Apollo alternative with server side rendering.
https://npm.im/graphql-react
MIT License
717 stars 22 forks source link

How to use useGraphQL hooks when handleLoadMore functions trigger? #50

Closed gauravverma029 closed 4 years ago

gauravverma029 commented 4 years ago

I am trying to implement scroll pagination. For this on handleLoadMore, I want to fire graphql query and with new data want to update my state.

This code is not working for me :-

getting error 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:

 const handleLoadMore = () => {
    setLoading(true);
    const { loading, cacheValue = {} } = useGraphQL({
      fetchOptionsOverride(options) {
        options.url = GRAPHQL_URL;
      },
      operation: {
        query: SEARCH_PROPERTYGROUPS_QUERY,
        variables: { ...queryVariables },
      },
      loadOnMount: true,
      loadOnReload: true,
      loadOnReset: true,
    }); 

   setItems([...items, newPage.items]); // Want to update my state with cacheValue data

  };
jaydenseric commented 4 years ago

Please see the rules of React hooks:

https://reactjs.org/docs/hooks-rules.html

useGraphQL, like all React hooks, can only be used at the top level of a functional React component’s scope.

If you want to programatically run a query, you can use the GraphQL instance method operate directly.

You can get the GraphQL instance in a component like this:

import { useContext } from 'react';
import { GraphQLContext } from 'graphql-react';

Then in your functional component scope:

const graphql = useContext(GraphQLContext);

Note that most of the time the “correct” solution involves useGraphQL. There is a clever recursive technique you can use to get pagination going with it, but explaining it properly would take a lengthy blog post.