Skip to content

Instantly share code, notes, and snippets.

@3lpsy
Created August 2, 2021 03:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save 3lpsy/55da83779a50f603a78ae8331e360a37 to your computer and use it in GitHub Desktop.
Save 3lpsy/55da83779a50f603a78ae8331e360a37 to your computer and use it in GitHub Desktop.
Svelte Store with Custom Class in Typescript
/*
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}
*/
@amr3k
Copy link

amr3k commented Dec 28, 2021

Please fix the typo in line 24
subscribe instead of ubscribe.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment