Skip to content

Repository files navigation

Angular SWR

Data fetching for Angular 14+

Usage

Create a service that fetches data

constendpoint="https://jsonplaceholder.typicode.com/todos"
@Injectable({providedIn: "root"})exportclassFetcherimplementsFetchable<Todo[]>{privatehttp=inject(HttpClient)fetch(userId: string){returnthis.http.get(endpoint,{params: { userId }})}}

Create a resource

import{createResource,revalidateOnFocus,refreshInterval,revalidateOnReconnect}from"@mmuscat/angular-swr"exportconstTODOS=createResource(Fetcher,{features: [revalidateOnFocus,revalidateOnReconnect,refreshInterval(60_000)]})

Provide and use resource in component

import{TODOS}from"./resource"
@Component({selector: "app-todos",templateUrl: "./todos.component.html",providers: [TODOS],})exportclassTodosComponent{protectedtodos=inject(TODOS)
@Input()userId: stringngOnChanges(){this.todos.fetch(this.userId)}}

Read values in template

<!-- todos.component.html --><div*ngIf="todos.error">
Something went wrong
<button(click)="todos.revalidate()">Retry</button></div><spinner*ngIf="todos.pending"></spinner><todo*ngFor="let todo of todos.value" [value]="todo"></todo>

Options

exportinterfaceResourceOptions{providedIn?: Type<any>|"root"|"platform"|"any"|nullimmutable?: booleantimeoutMs?: numberdedupeMs?: numbercache?: booleanrefetchIfStale?: booleanserialize?: (...params: any[])=>stringfeatures?: ResourceFeatureWithOptions<{}>[]}
propertydefaultdescription
providedInnullConfigure which module the resource is provided in
immutablefalsePrevent refetching a resource that is already cached with the given params
timeoutMs3000How long a resource should wait after fetching without receiving a response before it is marked as slow
dedupeMs2000How long a resource should wait before allowing a duplicate fetch with the same params
cachetrueDisables caching when set to false, useful when fetch is used to send data
revalidateIfStaletrueControl whether a resource should revalidate when mounted if there is stale data
serializeJSON.stringifySerializer used to stringify fetch parameters
featuresvoidA list of ResourceFeatureWithOptions that add additional behaviours to the resource

Adding Features

Resource behavior can be customised by adding features.

revalidateOnFocus

Revalidate a resource every time the current page receives window focus.

revalidateOnReconnect

Revalidate a resource every time the network connection comes back online.

refreshInterval

Revalidate a resource periodically according to a timer.

Writing Custom Features

Create a class that implements the ResourceFeature interface.

interfaceResourceFeature<Textends{}>{onInit?(resource: Resource,options: T): voidonConnect?(resource: Resource,options: T): voidonDisconnect?(resource: Resource,options: T): voidonDestroy?(resource: Resource,options: T): void}

Example

import{createFeature,Fetchable,Resource,ResourceFeature}from"@mmuscat/angular-swr"interfaceLoggerOptions{token?: Type<{log: (resource: Resource)=>void}>}
@Injectable({providedIn: "root"})exportclassLoggerimplementsResourceFeature<LoggerOptions>{privateinjector=inject(INJECTOR)onInit(resource: Resource<T>,{ token }: LoggerOptions){constlogger=this.injector.get(token,console)resource.subscribe(()=>{logger.log(resource)})}}exportfunctionlogger(token: Type<any>){returncreateFeature(Logger,{ token })}

Usage

@Injectable({providedIn: "root"})classMyLogger{log(resource: Resource){// log implementation}}constRESOURCE=createResource(Fetcher,{features: [logger(MyLogger)]})

About

Data fetching for Angular

Resources

Stars

9 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages