Create a Svelte Store
Svelte store is used to secure the "/admin" page and to keep track of the currently signed-in user. Learn how to use the Svelte store for your web application.
We'll cover the following
To secure the /admin
page and to keep track of the currently signed-in user, we are going to create a Svelte store. As soon as a user signs in, we set the user
information in the store. When a user signs out, we remove the user information.
This store can then be used anywhere in the web application. For example, we will also use it to display “Sign In” vs. “Sign out” in the navigation bar, depending on whether a user is signed in or not.
Creating a Svelte store to keep track of the current user
To create the user store, we have added a new services/web/src/stores/user.js
file. Add the following code to this file:
import { writable } from "svelte/store";
const createStore = () => {
const { subscribe, set } = writable(null);
// "subscribe" method that allows interested parties to be notified whenever the store value changes.
// "set" method is used to change the value in the store.
return {
subscribe,
signIn: (user) => set(user),
signOut: () => set(null),
};
};
export const currentUser = createStore();
Our custom store provides a signIn
and a signOut
function to make the code more readable. The subscribe function allows us to auto-subscribe to the store so that Svelte updates whenever a user signs in or out.
Keep the user store updated
The new user store needs to be informed whenever a user signs in or out. Firebase
Authentication provides a way to do that in the form of an onAuthStateChanged()
event handler. In a true component-focused manner, we are going to encapsulate that logic in a Svelte component at services/web/src/components/user-observer.svelte
:
Get hands-on with 1400+ tech skills courses.