apoolo uselaxyQuery bypass cache

Apollo UseQuery Bypass Cache

If you are using Apollo Client, you might have come across a situation where you want to bypass the cache and fetch fresh data from the server. This is where Apollo's useQuery hook comes in handy. By default, Apollo caches the results of queries and returns the cached data if the same query is executed again. However, sometimes you might want to bypass this cache and fetch fresh data from the server.

Using useQuery Hook

To bypass the cache and fetch fresh data from the server, you can pass fetchPolicy: "network-only" option to the useQuery hook. This will force Apollo to fetch data from the server and not use the cached data.


import { useQuery } from '@apollo/client';
import { QUERY } from './constants';

function MyComponent() {
  const { loading, error, data } = useQuery(QUERY, {
    fetchPolicy: "network-only"
  });

  if (loading) return 'Loading...';
  if (error) return `Error! ${error.message}`;

  return (
    <div>
      <p>{data.message}</p>
    </div>
  );
}

Using a Custom Query Hook

If you have multiple components that need to bypass the cache and fetch fresh data from the server, you might want to create a custom query hook that wraps around Apollo's useQuery hook.

Here is an example of a custom query hook that takes fetchPolicy as an argument:


import { useQuery } from '@apollo/client';
import { QUERY } from './constants';

function useCustomQuery(fetchPolicy) {
  return useQuery(QUERY, {
    fetchPolicy
  });
}

export default useCustomQuery;

You can then use this custom query hook in your components:


import useCustomQuery from './useCustomQuery';

function MyComponent() {
  const { loading, error, data } = useCustomQuery("network-only");

  if (loading) return 'Loading...';
  if (error) return `Error! ${error.message}`;

  return (
    <div>
      <p>{data.message}</p>
    </div>
  );
}

Conclusion

Bypassing the cache and fetching fresh data from the server is a common requirement in many applications. With Apollo Client, you can achieve this by using the useQuery hook and passing fetchPolicy: "network-only" option. You can also create a custom query hook that wraps around Apollo's useQuery hook to make it easier to use in multiple components.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe