Overcome endless looping when executing useQuery (ApolloClient) by defining a new client

I need to define “client” when running “useQuery”, but I get endless looping.

I wrote the code as below:

const QueryKTP = gql`
  query {
    documents(transactionId:"${transactionId}", input: [
      {documentType:"KTP"}
    ]){
      documentResponses{
        documentType
        documentBase64
      }
      responseDescription
      responseCode
     message
    }
  }`

const anotherClient = new ApolloClient({
  uri: "https://my-url/online-service/graphql"
});

const { data, loading } = useQuery(QueryKTP, {client: anotherClient});

If I change the script above to be like below (remove new client), looping no longer occurs.

const { data, loading } = useQuery(QueryKTP);

What do I need to fix? Thank you

Answer

Finally, I’ve figured out. I faced the same problem and I solved it by excluding new ApolloClient from render function.

Actually, I don’t see render function from your code, but in my case, it was something like this:

Before

export default function MyComponent () {
  const anotherClient = new ApolloClient({
    uri: "https://my-url/online-service/graphql"
  });
  const { data, loading } = useQuery(QueryKTP, {client: anotherClient});
}

After

const anotherClient = new ApolloClient({
  uri: "https://my-url/online-service/graphql"
});
export default function MyComponent () {
  const { data, loading } = useQuery(QueryKTP, {client: anotherClient});
}

In my case, it helped. You should know, that in similar cases just look to new keyword. For example, guys often meet the same bug with an infinite loop, when they use new Date() in the render function

Leave a Reply

Your email address will not be published. Required fields are marked *