Tuhin
Tuhin

Reputation: 3373

How to restrict api call by useQuery to be called only once?

I've following component, which has a date variable. On each re render, date variable is getting updated. Now the the problem is as I've assigned date to a query variable, graphql fetches again and again infinitely. I have debugged the code and found apollo is Observing on date variable, when it is receiving a new value, it is to re.

import React from 'react';
import { getISODate } from '../../dateUtils';
import { useQuery } from '@apollo/react-hooks';
import { GET_EXPENSE_STATUS } from '../../queries';
import get from 'lodash/get';

const ExpenseStatus = (props) => {
  const date = getISODate(); // returns current date as ISO String Format
  const { loading, error, data } = useQuery(GET_EXPENSE_STATUS, {
    variables: {
      date
    }
  });
  if (error) return <p>Error :(</p>;
  return(
    <div>
       {get(data, 'expenseStatus.value')}
    </div>
  );
};

I also tried with useLazyQuery. But no luck.

 const date = getISODate(); // returns current date in ISO String

 const [loadExpenseStatus, { loading, error, data }] = useLazyQuery(GET_EXPENSE_STATUS, {
     variables: {
       date
     }
 });

 useEffect(() => {
   if(!called) {
     loadExpenseStatus();
   }
 }, []);

So, Is there any way, I can skip this Observer? I just want to receive the fetch call once.

Upvotes: 4

Views: 17085

Answers (1)

xadm
xadm

Reputation: 8418

Two solutions possible, 1st (initial value 'freezing'):

const [staticDate] = useState( getISODate() );
const { loading, error, data } = useQuery(GET_EXPENSE_STATUS, {
  variables: {
    date: staticDate
  }
});

or simple const [date] = useState( getISODate() ); and variables: { date } ... when date with current value required in other places.

2nd one (when no 'date' value required in output/render):

const [loadExpenseStatus, { loading, error, data }] = useLazyQuery(GET_EXPENSE_STATUS);

useEffect(() => {
  loadExpenseStatus( {
    variables: {
      date: getISODate()
    }
  } );
}, []); // called once

docs: https://www.apollographql.com/docs/react/data/queries/#executing-queries-manually

Upvotes: 8

Related Questions