How to optionally turn off Apollo caching

69 Views Asked by At

What I need is to NOT cach the data if Query has a specific parameter.

I have this hook for queries, it has dafault 'cache-first' value for fetchPolicy property (default Apollo behaviour):

import { getItem } from 'utilities/sessionStorage';

const useStoreApolloClient = ({ query, parameters = {}, fetchPolicy = 'cache-first' }) => {
    const { store: storeId, timezone } = getItem(userInfo, true);

    const [getData, { data, error, loading }] = useLazyQuery(query, {
        variables: {
            storeId,
            timezone,
            ...parameters
        },
        fetchPolicy
    });

    useEffect(() => {
        if (!error) {
            getData();
        }
    }, [getData, error]);

    return {
        data,
        error,
        getData,
        loading
    };
};

And here I'm trying to optionaly change Fetch Policy when fetching the data. If "timePeriod" property is "D" fetchPolicy value is "no-cache":

    const {
        dateMode: timePeriod,
        date: { endDate: toDate, startDate: fromDate, endTime, startTime }
    } = useRecoilValue(kpiDateAtom);

    const {
        data: chartData,
        loading,
        error
    } = useStoreApolloClient({
        parameters: {
            fromDate,
            fromTime: parseInt(startTime),
            timePeriod,
            toDate,
            toTime: parseInt(endTime),
        },
        query: STORE_KPI_CHARTS_DATA(generateQueryFor(checkedCharts)),
        fetchPolicy: timePeriod === 'D' ? 'no-cache' : 'cache-first'
    });

But it's just doesen't work. If you gonna change default fetchPolicy parameter and hardcode any value there, it's just always will be the same. There is no way to make it changed optionaly.

2

There are 2 best solutions below

0
phry On BEST ANSWER

You can use the nextFetchPolicy callback notation:

        fetchPolicy: timePeriod === 'D' ? 'no-cache' : 'cache-first',
        nextFetchPolicy(lastFetchPolicy, { reason, options }){
            if (reason == 'variables-changed') {
                return options.variables.timePeriod === 'D' ? 'no-cache' : 'cache-first'
            }
            return lastFetchPolicy;
        }
0
Reza Hatami On

You can set defaultOptions to your client like this:

const defaultOptions = {
      watchQuery: {
        fetchPolicy: 'network-only',
        errorPolicy: 'ignore',
      },
      query: {
        fetchPolicy: 'network-only',
        errorPolicy: 'all',
      },
    }

const client = new ApolloClient({
    link: concat(authMiddleware, httpLink),
    cache: new InMemoryCache(),
    defaultOptions: defaultOptions,

});