0

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 Answers 2

0

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;
        }
Sign up to request clarification or add additional context in comments.

Comments

0

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,

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.