File tree Expand file tree Collapse file tree 4 files changed +43
-1
lines changed Expand file tree Collapse file tree 4 files changed +43
-1
lines changed Original file line number Diff line number Diff line change 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+ } ;
Original file line number Diff line number Diff line change 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+ } ;
Original file line number Diff line number Diff line change 11export { getValuesFromCacheByKeysStartingWith } from "./cache" ;
2+ export { initClient } from "./context" ;
23export { globalIsFetching } from "./indicator" ;
34export { useSWR } from "./swr" ;
Original file line number Diff line number Diff line change @@ -3,6 +3,8 @@ import { newFSM } from "@cicerchie/fsm";
33import { writable } from "svelte/store" ;
44
55import { swrMachine } from "./machine" ;
6+ import { getClient } from "./context" ;
7+ import { newClient } from "./client" ;
68
79interface SWROptions < T > {
810 enabled ?: boolean ;
@@ -45,6 +47,8 @@ const defaultSWRParams = {
4547} ;
4648
4749export 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 > ) {
You can’t perform that action at this time.
0 commit comments