DEV Community

loading...
Cover image for Refetch active Apollo queries in PWA Studio on user action

Refetch active Apollo queries in PWA Studio on user action

jordaneisenburg profile image Jordan Eisenburger ・1 min read

In some use cases you need to refetch your GraphQL queries on a user action. To do this you need to tell your <query> component to refetch the data. Triggering this can be hard to do from a different part of your code base.

As an example:
I have a B2B webshop. The customer is on the product page and can see regular/general prices. But when he logs in the product info/prices need to update to reflect his special info/prices.

There is no easy way to do this besides either doing a page reload that will force reload the whole page and queries or use Apollo's client.resetStore() but this will reset the whole store and refetch all active queries.

To do this more surgical we can use something like this snippet.

// refetchQueriesByName.js

const findQueries = (manager, names) => {
    const matching = [];
    manager.queries.forEach(q => {
        if (q.observableQuery && names.includes(q.observableQuery.queryName)) {
            matching.push(q);
        }
    });
    return matching;
};

export const refetchQueriesByName = (names, client) => {
    return Promise.all(
        findQueries(client.queryManager, names).map(q =>
            q.observableQuery.refetch(),
        ),
    );
};
Enter fullscreen mode Exit fullscreen mode

Implementation

// packages/peregrine/lib/talons/SignIn/useSignIn.js

import { refetchQueriesByName } from 'PATH_TO/refetchQueriesByName';

    const handleSubmit = useCallback(
        async ({ email, password }) => {
            setIsSigningIn(true);
            try {

                ...

                // Place somewhere after 'const destinationCartId = await retrieveCartId();'


                // These names are the actual names you declared in your graphql files
                await refetchQueriesByName(
                    [
                        'productDetail',
                        'relatedProducts',
                    ],
                    apolloClient
                ); 

                ...

})
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide