Skip to content

Commit ee64b62

Browse files
committed
fix: add Client and methods for Svelte Context; add onError handling in receiveFn()
1 parent 9f798c1 commit ee64b62

File tree

4 files changed

+43
-1
lines changed

4 files changed

+43
-1
lines changed

src/lib/client.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
export interface GlobalOptions {
2+
onError?: (error: Error) => void;
3+
}
4+
5+
export interface Client {
6+
options: GlobalOptions;
7+
}
8+
9+
const defaultGlobalOptions: GlobalOptions = {};
10+
11+
export const newClient = (options: GlobalOptions): Client => {
12+
options = { ...defaultGlobalOptions, ...options };
13+
14+
return { options };
15+
};

src/lib/context.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { setContext, getContext } from "svelte";
2+
3+
import type { Client, GlobalOptions } from "./client";
4+
import { newClient } from "./client";
5+
6+
const key = "@cicerchie_svelte-swr";
7+
8+
export const getClient = (): Client => getContext(key);
9+
10+
export const setClient = (client: Client): void => setContext(key, client);
11+
12+
export const initClient = (options: GlobalOptions): Client => {
13+
const client = newClient(options);
14+
setClient(client);
15+
return client;
16+
};

src/lib/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
export { getValuesFromCacheByKeysStartingWith } from "./cache";
2+
export { initClient } from "./context";
23
export { globalIsFetching } from "./indicator";
34
export { useSWR } from "./swr";

src/lib/swr.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { newFSM } from "@cicerchie/fsm";
33
import { writable } from "svelte/store";
44

55
import { swrMachine } from "./machine";
6+
import { getClient } from "./context";
7+
import { newClient } from "./client";
68

79
interface SWROptions<T> {
810
enabled?: boolean;
@@ -45,6 +47,8 @@ const defaultSWRParams = {
4547
};
4648

4749
export function useSWR<T>(): SWRStore<T> {
50+
const client = getClient() || newClient({});
51+
4852
// const store = writable<SWRStore<T>>({ ...defaultSWRStore }, () => {
4953
// fsm.setEnabled(true);
5054
// return () => {
@@ -56,7 +60,13 @@ export function useSWR<T>(): SWRStore<T> {
5660
const fsm = newFSM({
5761
config: swrMachine,
5862
context: { ...defaultSWRStore },
59-
receiveFn: (state, ctx) => store.set({ state, ...ctx }),
63+
receiveFn: (state, ctx) => {
64+
store.set({ state, ...ctx });
65+
66+
if (client.options.onError && ctx.error) {
67+
client.options.onError(ctx.error);
68+
}
69+
},
6070
});
6171

6272
function update(params: SWRParams<T>) {

0 commit comments

Comments
 (0)