Skip to Content
Effetch Query
The cache

Use the cache outside Effect

Read and write the cache from code that isn't Effect.

Code outside Effect, such as a router loader or an event handler, can't yield* a cache function (Use the cache from Effect). The client has a method for each, which returns a Promise and does what its Query function does:

The examples import client.ts and todos.ts from Getting started.

MethodReturns
client.fetch(query)Promise<A>, rejected as the query fails, so a router's redirect gets through.
client.prefetch(query)Promise<void>, resolved when the fetch settles. Never rejects.
client.invalidate(target)Promise<void>, resolved at once.
client.refetch(target)Promise<void>, resolved when the queries in use have settled.
client.reset(target)Promise<void>, resolved at once.
client.clear(target)Promise<void>, resolved at once.

Here they are in a loader and two event handlers:

import {  } from "./client.js";
import { ,  } from "./todos.js";

// A router loader. It rejects as the query fails, and stops waiting when
// the navigation is cancelled.
export const  = (: number, : AbortSignal) =>
  .(({ : {  } }), {  });

// Hovering a link starts the next screen's fetch. It never rejects.
export const  = () => {
  void .(({ : { : false } }));
};

// Pull to refresh: the spinner stops once the lists in use have settled.
export const  = () => .();

Without a target, invalidate, refetch, reset and clear act on every query. They reject only with a defect, such as a Query.KeyHoldsTargetError for a key that holds queries. On a disposed client, they do nothing. fetch and prefetch take { signal } to stop waiting when it aborts.

Read without waiting. To read the cache where you can't wait for a promise, such as a form listener, QueryClient.get(queryClient, query) returns the cached value as an Option, as Query.get does. It never fetches:

import * as  from "effect/Option";

import {  } from "@monarcode/effetch-query";

import {  } from "./client.js";
import {  } from "./todos.js";

export const  = (: number): string =>
  .(.(, ({ : {  } })), {
    : () => "",
    : () => .,
  });

Run any Effect. For anything else, queryClient.runPromise(effect) runs an Effect with your services and the client, and rejects with its error if it fails. queryClient.runPromiseExit(effect) resolves with the Exit instead, so it never rejects. Both take { signal } to interrupt the Effect when the signal aborts. In a component, useQueryClient() returns the client.

When you're done with a client, such as one made per request on a server, queryClient.dispose() releases everything it owns (Client members).