Created
August 2, 2021 03:37
-
-
Save 3lpsy/55da83779a50f603a78ae8331e360a37 to your computer and use it in GitHub Desktop.
Svelte Store with Custom Class in Typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
I recently jumped into svelte programming and wanted to create a class/singleton that could double as a reactive writable store. | |
I did things very wrong until people on the discord confirmed how wrong my implementation was so I wanted to provide a simple example. | |
So below is a simple account store you can use. I'm not sure if it's optimal or even correct, but it's better than my first attempt. | |
Feel free to provide feedback. | |
*/ | |
``` | |
import { writable } from "svelte/store"; | |
// fake stuff for example | |
import {AuthUser, GuestUser, authService} from "./utils"; | |
export default class Account { | |
public subscribe: Function; | |
private _set: Function; | |
private _update: Function; | |
private authUser: AuthUser; | |
private isAuthenticated: Boolean; | |
constructor() { | |
this.authUser = new GuestUser(); | |
this.isAuthenticated = false; | |
let {subscribe, set, update} = writable(this); | |
this.subscribe = ubscribe; | |
this._set = set; | |
this._update = update; | |
} | |
login(form: AuthForm): Boolean { | |
return authService.login(form).then((authUser) => { | |
this._update((that) => { | |
that.authUser = authUser; | |
that.isAuthenticated = true; | |
return that; | |
}); | |
return true; | |
}).catch((e: InvalidLogin) => { | |
this.clearUser(); | |
return false; | |
}); | |
} | |
clearUser(): Boolean { | |
this._update((that) => { | |
that.authUser = new GuestUser(); | |
thas.isAuthenticated = false; | |
}); | |
return true; | |
} | |
} | |
/* | |
Then in your .svelte, you could import a singleton/instance of the above class and use it as a store: | |
{#if $account.isAuthenticated } | |
<p> User: $account.authUser.name </p> | |
{:else} | |
<p> Need to login </p | |
{/if} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please fix the typo in line 24
subscribe
instead ofubscribe
.