reactjsgraphqlapollo-client

Data Retrieval not getting updated until after a few requests in my Apollo GraphQL request


I have this weird issue in my react application. My graphQL request does not seem to be fetching the most recent data even when the graphQL server returns the data. I am not really sure what is going on here.

This is my React Apollo graphQL query code

My Query

import { gql } from '@apollo/client';

export const getAvailabilityQuery = gql`
    query User {
        user {
            availability {
                name
                times {
                    start
                    end
                }
            }
        }
    }
`;

This is how I am fetching the data

import { useUserWorkAvailabilityQuery } from './userAvailabilityQuery.gql.generated';
const { data, loading } = useUserWorkAvailabilityQuery();

Not sure what I am doing wrong


Solution

  • The issue is happening because of how the network policy in Apollo Client is set up in React. The network policy in Apollo Client is set to cache-first by default. This means that Apollo Client first attempts to fulfill the query from the cache. If all requested data is present, it returns that data. Otherwise, it fetches the data from the network and caches it for future use.

    This policy minimizes network requests but may serve stale data if the cache isn't updated.

    To fix your issue, modify

    const { data, loading } = useUserWorkAvailabilityQuery();
    

    to

    const { data, loading } = useUserWorkAvailabilityQuery({
        fetchPolicy: 'network-only'
    });
    

    This will ensure that Apollo client only fetches data from the server and not the cache