Skip to content

5. context

Naveen Mathew edited this page Apr 8, 2024 · 2 revisions

useContext

A Qwery has to be placed within a QweryContext to utilize caching. QweryContext provides CacheStore and RequestManager to all subscribers.

On the server, CacheStore is a no-op cache though a custom one can be specified. In the browser, CacheStore is a Map by default though a custom one can be specified.

A CacheStore implements the following interfaces

interface CacheStore {
  has: (queryKey: Serializable) => boolean;
  get: (queryKey: Serializable) => void | CacheValue | Promise<CacheValue>;
  set: (queryKey: Serializable, value: CacheValue) => void;
  delete: (queryKey: Serializable) => void;
  clear?: () => void;
}

type CacheValue = Record<string | symbol | number, any> | unknown[];

interface Serializable {
  toString: () => string;
}

A RequestManager implements the following interface

export interface QweryRequestManager {
  has: (queryKey: Serializable) => boolean;
  get: (queryKey: Serializable) => any;
  set: (queryKey: Serializable, value: any) => void;
  delete: (queryKey: Serializable) => void;
}

For the various frameworks, QweryContext can be supplied using:

  • React: QweryContext and QweryProvider
  • Vue: provideQweryContext and useQweryContext
  • Svelte: setQweryContext and useQweryContext

Options

QweryContext has the following options available:

Optional

  • store: an optional CacheStore to be used, can be used to implement an asynchronous CacheStore

  • requestManager: an optional RequestManager to deduplicate requests

Result

  • QweryContextValue: which provides access to both the cache and the requestManager
    • the cache can be used to store prefetched data
      • when setting prefetched data for GraphQL, making use of normalized caching requires a __typename field to be specified on each entity
    • there is no use in using the requestManager directly