Home > front end >  Multiple useLazyQuery hooks (Apollo Client) in React Function Component
Multiple useLazyQuery hooks (Apollo Client) in React Function Component

Time:11-02

I am trying to include two Apollo-Client useLazyQuery hooks in my function component. Either works fine alone with the other one commented out, but as soon as I include both, the second one does nothing. Any ideas?

export default function MainScreen(props) {

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

  const [validateWhenMounting, { loading, error, data }] = useLazyQuery(
    validateSessionToken,
    {
      onCompleted: (data) => console.log('data', data),
    },
  );

  const [validate, { loading: loading2, error: error2, data: data2 }] =
    useLazyQuery(validateSessionTokenWhenSending, {
      onCompleted: (data2) => console.log('data2', data2),
    });


  const handleSendFirstMessage = (selectedCategory, title, messageText) => {
    console.log(selectedCategory, title, messageText);
    validate();
  };
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Figured it out: Adding the key-value pair fetchPolicy: 'network-only', after onCompleted does the trick. It seems that otherwise, no query is being conducted due to caching...

CodePudding user response:

This is the pattern that I was talking about and mentioned in the comments:

const dummyComponent = () => {
  const [lazyQuery] = useLazyQuery(DUMMY_QUERY, {variables: dummyVariable,
   onCompleted: data => // -> some code here, you can also accept an state dispatch function here for manipulating some state outside
   onError: error => // -> you can accept state dispatch function here to manipulate state from outside
 });
  return null;
}

this is also a pattern that you are going to need sometimes

  • Related