Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add useFetchPolicyAfterHydration hook #329

Open
mariusc23 opened this issue Jan 25, 2023 · 0 comments
Open

Add useFetchPolicyAfterHydration hook #329

mariusc23 opened this issue Jan 25, 2023 · 0 comments
Labels
enhancement New feature or request @uplift-ltd/apollo

Comments

@mariusc23
Copy link
Collaborator

mariusc23 commented Jan 25, 2023

Change the fetch policy from cache-first to cache-and-network on mount to fix apollographql/apollo-client#8669

import { WatchQueryFetchPolicy } from "@apollo/client";
import { useHydrated } from "./useHydrated";

export type UseFetchPoliciesAfterHydrationParams = {
  afterHydrationFetchPolicy?: WatchQueryFetchPolicy;
  afterHydrationNextFetchPolicy?: WatchQueryFetchPolicy;

  beforeHydrationFetchPolicy?: WatchQueryFetchPolicy;
  beforeHydrationNextFetchPolicy?: WatchQueryFetchPolicy;
};

/**
 * useFetchPoliciesAfterHydration
 *
 * To get around an issue with SSR/Apollo showing the incorrect loading status
 * we're going to load the initial request with cache-first and then
 * swap out the fetchPolicy so that the loading indicator is not incorrectly shown
 * while reading from the apollo cache
 * https://github.com/apollographql/apollo-client/issues/8669
 *
 *
 */
export function useFetchPoliciesAfterHydration({
  afterHydrationFetchPolicy = "cache-and-network",
  afterHydrationNextFetchPolicy,

  beforeHydrationFetchPolicy = "cache-first",
  beforeHydrationNextFetchPolicy = "cache-first",
}: UseFetchPoliciesAfterHydrationParams = {}) {
  const isHydrated = useHydrated();

  return isHydrated
    ? {
        fetchPolicy: afterHydrationFetchPolicy,
        nextFetchPolicy: afterHydrationNextFetchPolicy ?? beforeHydrationNextFetchPolicy,
      }
    : { fetchPolicy: beforeHydrationFetchPolicy, nextFetchPolicy: beforeHydrationNextFetchPolicy };
}
@mariusc23 mariusc23 changed the title Add useFetchPolicyAfterHydrationHook Add useFetchPolicyAfterHydration hook Jan 25, 2023
@mariusc23 mariusc23 added enhancement New feature or request @uplift-ltd/apollo labels Feb 11, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request @uplift-ltd/apollo
Projects
None yet
Development

No branches or pull requests

1 participant