🔥 Firebase Svelte v2

🔥 Firebase Svelte

Firebase Svelte is a collection of stores and components that make it easy to integrate realtime firebase services in your Svelte app. We currently support Auth, Firestore, Realtime DB, Remote Config and Storage.

+page.svelte
<script>
  import { createUserStore } from 'firebase-svelte';

  const user = createUserStore(/* Auth Instance */);
</script>

<h1>Hello {$user.displayName}</h1>
				

Okay but why?

Let's be honest. Firebase APIs can sometimes be annoying to work with with their callbacks and all, although they are very powerful. Firebase Svelte aims to help to :

  • Access realtime data from Firebase using Svelte stores
  • Automatically disposing of data subscriptions
  • Enhance the typescript experience using firebase
  • Provide easier ways of getting and showing data using components
  • Have a maintained and up-to-date library of consistent firebase APIs

Stores

Every store is reactive so it updates when the data changes, and it will unsubscribe when the component is unmounted.

Some stores also have methods to update the data, like the update or set method on the doc store. These methods will not update the data in the store, which allows you to create optimistic updates.

+page.svelte
<script>
  import { createDocStore } from 'firebase-svelte';
  import { firestore } from '$lib/firebase';

  const post = createDocStore(firestore, 'posts/123');

  function updatePost() {
    post.update({ title: 'New Title' });
  }
</script>

<h1>{$post.title}</h1>

<section class="prose">
  <p>{$post.content}</p>
</section>

<button on:click={updatePost}>Update</button>
				

Components

Altough components also use stores, they might be easier to use for some cases such as simply getting data from a collection or a document.

Also, stacking components is a great way to make your app more modular and reusable, as the example below shows.

+page.svelte
<script> import { Collection, Doc, User } from 'firebase-svelte'; import { firestore, auth } from '$lib/firebase'; </script> <!-- 1. 🔥 Firebase App --> <FirebaseApp {auth} {firestore}> <!-- 2. 🧑‍🤝‍🧑 User --> <User let:user> <p>Hello, {user.displayName}</p> <!-- 3. 📄 Document, for example owned by a user --> <Doc ref={`posts/${user.uid}`} let:data={post} let:ref={postRef} > <h2>{post.title}</h2> <!-- 4. 📚 Collection, for example comments on a post --> <Collection ref={`${postRef.path}/comments`} let:data={comments} > {#each comments as comment} <p>{comment.content}</p> {/each}