Solid hooks for Firebase v9.

Overview

solid-firebase

Solid hooks for Firebase.

Quick start

Install it:

yarn add firebase solid-firebase

Configure firebase app:

import { render } from 'solid-js/web'
import { FirebaseProvider } from 'solid-firebase'
import App from './App'

const firebaseConfig = {...}

render(
  () => (
    <FirebaseProvider config={config}>
      <App />
    </FirebaseProvider>
  ),
  document.getElementById('root') as HTMLElement,
)

Hooks

All available hooks returns a readonly proxy object with keys loading, error and data. Do not destructure as it will lose reactivity.

If you want to access the firebase instance, you can use the useFirebaseApp hook.

Authentication

useAuth is a Firebase Auth binding to easily react to changes in the users' authentication status.

import { Switch, Match } from 'solid-js'
import { GoogleAuthProvider, getAuth, signInWithPopup } from 'firebase/auth'
import { useAuth } from 'solid-firebase'

const Login = () => {
  const auth = getAuth()
  const signIn = () => signInWithPopup(auth, new GoogleAuthProvider())

  return <button onClick={signIn}>Sign In with Google</button>
}

const App = () => {
  const auth = getAuth()
  const state = useAuth(auth)

  return (
    <Switch>
      <Match when={state.loading}>
        <p>Loading...</p>
      </Match>
      <Match when={state.error}>
        <Login />
      </Match>
      <Match when={state.data}>
        <User data={state.data} />
      </Match>
    </Switch>
  )
}

Cloud Firestore

useFirestore is a Cloud Firestore binding that makes it straightforward to always keep your local data in sync with remotes databases.

import { Match, Switch } from 'solid-js'
import { collection, getFirestore } from 'firebase/firestore'
import { useFirestore } from 'solid-firebase'

const App = () => {
  const db = getFirestore()
  const todos = useFirestore(collection(db, 'todos'))

  // or for doc reference
  const todo = useFirestore(doc(db, 'todos', 'todo-id'))

  return (
    <Switch>
      <Match when={todos.loading}>
        <p>Loading...</p>
      </Match>
      <Match when={todos.error}>
        <p>An error occurred.</p>
      </Match>
      <Match when={todos.data}>
        <TodoList data={todos.data} />
      </Match>
    </Switch>
  )
}

Realtime Database

useDatabase is a Realtime Database binding that makes it straightforward to always keep your local data in sync with remotes databases.

import { Match, Switch } from 'solid-js'
import { getDatabase, ref } from 'firebase/database'
import { useDatabase } from 'solid-firebase'

const App = () => {
  const db = getDatabase()
  const todos = useDatabase(ref(db, 'todos'))

  return (
    <Switch>
      <Match when={todos.loading}>
        <p>Loading...</p>
      </Match>
      <Match when={todos.error}>
        <p>An error occurred.</p>
      </Match>
      <Match when={todos.data}>
        <TodoList data={todos.data} />
      </Match>
    </Switch>
  )
}

Cloud Storage

useDownloadURL is a hook that wraps the getDownloadURL method of Cloud Storage.

import { Match, Switch } from 'solid-js'
import { getStorage, ref } from 'firebase/storage'
import { useDownloadURL } from 'solid-firebase'

const App = () => {
  const storage = getStorage()
  const state = useDownloadURL(ref(
    storage,
    'images/yourimage.jpg',
  ))

  return (
    <Switch>
      <Match when={state.loading}>
        <p>Download URL: Loading...</p>
      </Match>
      <Match when={state.error}>
        <p>Error: {state.error?.name}</p>
      </Match>
      <Match when={state.data}>
        <img src={state.data} alt="pic" />
      </Match>
    </Switch>
  )
}

License

MIT License © 2022 Robert Soriano

Comments
  • Error for using pnpm package

    Error for using pnpm package

    I'm getting init error in project that firebase app 'DEFAULT' is initialized, call initializeApp etc. from the basic example of usage firebase/auth I tried to debug it and copied source files from your project directly and error disappear. Probably it is something with how package manager work with contexts in your package but dont know actually

    opened by kirill-dev-pro 4
  • error with basic Firestore example

    error with basic Firestore example

    I get this error:

    FirebaseError: Firebase: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp() (app/no-app).
    
    //index.tsx
    
    /* @refresh reload */
    import { render } from 'solid-js/web';
    
    import { FirebaseProvider } from 'solid-firebase';
    import type { FirebaseOptions } from 'firebase/app';
    
    import './index.css';
    import App from './App';
    
    const firebaseConfig: FirebaseOptions = {
      apiKey: 'xxx',
      authDomain: 'xxx,
      databaseURL: 'xxx',
      projectId: 'xxx',
      storageBucket: 'xxx',
      messagingSenderId: 'xxx',
      appId: 'xxx',
    };
    
    render(
      () => (
        <FirebaseProvider config={firebaseConfig}>
          <App />
        </FirebaseProvider>
      ),
      document.getElementById('root') as HTMLElement
    );
    
    
    //App.tsx
    
    import { Component, Match, Switch } from 'solid-js';
    import { useFirestore } from 'solid-firebase';
    import { collection, getFirestore } from 'firebase/firestore';
    
    const App: Component = () => {
      const db = getFirestore();
      const test = useFirestore(collection(db, 'test'));
    
      return (
          <Switch>
            <Match when={test.loading}>
              <p>Loading...</p>
            </Match>
            <Match when={test.error}>
              <p>An error occurred.</p>
            </Match>
            <Match when={test.data}>{JSON.stringify(test)}</Match>
          </Switch>
      );
    };
    
    export default App;
    
    opened by redpandatronicsuk 3
  • Issues downloading from NPM registry.

    Issues downloading from NPM registry.

    Im having issues trying to install this using npm or pnpm, futhermore I get a 404 if I try to browse the pacakge on NPM https://www.npmjs.com/package/solid-firebase

    opened by Julioevm 2
  • Praise

    Praise

    Hi,

    I just wanted to give praise and applause for this great open-source project! I am currently migrating a complex app which uses Nextjs + React + Firebase Auth to Astro + Solidjs and your project helped a lot! It is shocking how small the footprint is in terms of kilobyte to download.

    Thanks a lot and please keep the project as lean and small as possible (modularized?) because at least in my use case the reason to move from React to Solid was to stop having these super huge Javascript codebases a frontend has to download.

    So thanks again and feel free to close the issue since it is not an issue 😬❤️

    opened by skreutzberger 1
  • fix: use existing auth state if it exists

    fix: use existing auth state if it exists

    This makes it such that when using these in nested components, i.e.:

    const app = initializeApp(firebaseConfig);
    const auth = getAuth(app);
    
    function App() {
        return <GuardedByAuth>
            <Route path='/profile' component={Profile} />
        </GuardedByAuth>
    }
    
    function GuardedByAuth() {
      const state = useAuth(auth)
    
      return (
        <Switch>
          <Match when={state.loading}>
            <p>Loading...</p>
          </Match>
          <Match when={state.error}>
            <Login />
          </Match>
          <Match when={state.data}>
            <Profile />
          </Match>
        </Switch>
      )
    }
    

    Do not get into a loading state again and do not have to handle it, i.e.:

    function Profile() { 
        const data = useAuth(auth); // not loading, since user already authenticated.
       return <div>data.user.name</div>
    }
    
    opened by ruudandriessen 1
  • FirebaseError: Expected type 'Query', but it was: a custom DocumentReference object

    FirebaseError: Expected type 'Query', but it was: a custom DocumentReference object

    After my original issue with FirebaseProvide not working (see #4), I resorted to just using the const app = initializeApp(firebaseConfig); in my class, but now I'm encountering a different kind of issue that seems to be related to the firebase implementation (might be due to firebase's breaking changes). Note: using Astro.

    Both

    const share = useFirestore(collection(db, 'shares'));
    

    and

    const share = useFirestore(doc(db, 'shares/'+shareid));
    

    Yield the same error in the code below.

    Code (Media.tsx file):

    import { Switch, Match } from 'solid-js';
    // import { render } from 'solid-js/web'
    import { initializeApp } from 'firebase/app'
    import { FirebaseProvider, useFirestore } from 'solid-firebase'
    import { doc, getFirestore } from 'firebase/firestore';
    // import { firebaseInstance } from '../services/global_state';
    
    
    const firebaseConfig = {...}
    
    export default function Media({ userid, shareid }) {
      const app = initializeApp(firebaseConfig);
      const db = getFirestore(app);
      // const share = useFirestore(collection(db, 'shares'));
      const share = useFirestore(doc(db, 'shares/'+shareid));
    
      return (
        <>
          <div class="media">
              <Switch children="">
                <Match when={share.loading} children="">
                  <p>Loading...</p>
                </Match>
                <Match when={share.error} children="">
                  <p>An error occurred.</p>
                </Match>
                <Match when={share.data} children="">
                  {JSON.stringify(share)}
                </Match>
              </Switch>
            </div>
        </>
      );
    }
    

    Error

    node:internal/process/promises:279
                triggerUncaughtException(err, true /* fromPromise */);
                ^
    
    [FirebaseError: Expected type 'Query', but it was: a custom DocumentReference object] {
      code: 'invalid-argument',
      customData: undefined,
      toString: [Function (anonymous)]
    }
    
    opened by noga-dev 1
  • removes firebase dependency

    removes firebase dependency

    Firebase should be installed as a dependency in the app using this package and then here only used as a peerDependency, otherwise you can get 2 instances of firebase which cause further issues.

    opened by redpandatronicsuk 1
  • Paginated query

    Paginated query

    Hello. Thank you for this library, I am really enjoying it. I was wondering if you will accept a PR to add a hook to use paginated queries. With the current primitives of this library is not possible, and I ended creating my own by modifying the useFirestore hook this library has.

    I think we should agree on the API then I can create a PR if you want. Regards

    opened by danielo515 2
Owner
Robert Soriano
[object Object]
Robert Soriano
Login of app to remind to drink water, using Firebase tools like Firebase Auth and Firebase Firestore

Water Reminder Login App Menu Contents Motivation Final Images How to download the project and run it? Technologies utilized Dev ?? Motivation This ap

Ilda Neta 10 Aug 22, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Tesodev-search-app - Personal Search App with React-Hooks

Tesodev-search-app Personal Search App with React-Hooks View on Heroku : [https://tesodev-staff-search-app.herokuapp.com/] Instructions Clone this rep

Rahmi Köse 1 Nov 10, 2022
Finance-Tracker - A basic finance-tracker application built using Next.js, React Hooks and Context API

Next.js + Tailwind CSS Example This example shows how to use Tailwind CSS (v3.0) with Next.js. It follows the steps outlined in the official Tailwind

Osemwengie Benjamin 1 Jan 2, 2022
Minimal Typescript / NextJS dApp template bootstrapped with wagmi Ethereum react hooks library.

Welcome to the NextJS wagmi starter template ?? Looking to get up and running with a Typescript / NextJS dApp as quickly as possible? You're in the ri

Seth 78 Jan 4, 2023
Atomico a micro-library for creating webcomponents using only functions, hooks and virtual-dom.

Atomico simplifies learning, workflow and maintenance when creating webcomponents. Scalable and reusable interfaces: with Atomico the code is simpler

Atomico 898 Dec 31, 2022
tRPC-ified SWR hooks

trpc-swr tRPC-ified SWR hooks Installation npm install trpc-swr @trpc/client Usage First, create your fully typed hooks using your router type: // trp

Sachin Raja 129 Jan 8, 2023
An extension of DOM-testing-library to provide hooks into the shadow dom

Why? Currently, DOM-testing-library does not support checking shadow roots for elements. This can be troublesome when you're looking for something wit

Konnor Rogers 28 Dec 13, 2022
wagmi hooks 🤝 Storybook interaction testing

A quick demonstration of how Storybook decorators can be combined with a mocked wagmi client to facilitate automated interaction testing for web3-enab

Mike Ryan 21 Dec 13, 2022
Generate meshes from signed distance functions and constructive solid geometry operations.

sdf-csg Generate meshes from signed distance functions and constructive solid geometry operations. This library is heavily based upon Inigo Quilez's 3

Rye Terrell 151 Oct 24, 2022
Solid.js library adding a services layer for global shared state.

Solid Services Services are "global" objects useful for features that require shared state or persistent connections. Example uses of services might i

Maciej Kwaśniak 55 Dec 30, 2022
solid material ui port (ported from blazor port)

solid-material-ui solid material ui port (porting from blazor port) In preparation for solid hack Turbo Mono-repository is used for component package

skclusive 18 Apr 30, 2022
[WIP] A solid directive for adding colorful shadows to images.

solid-cosha A solid directive for adding colorful shadows to images (based on cosha). Quick start Install it: yarn add solid-cosha Use it: import { co

Robert Soriano 2 Feb 3, 2022
Add cmd+k interface to your solid site

solid-ninja-keys Add cmd+k interface to your solid site. Built on top of ninja-keys. Quick start Install it: yarn add solid-ninja-keys Use it: import

Robert Soriano 20 Dec 19, 2022
A helper to use immer as Solid.js Signal to drive state

Solid Immer A helper to use immer as Solid.js Signal to drive state. Installation $ npm install solid-immer Usage Use createImmerSignal to create a im

Shuaiqi Wang 67 Nov 22, 2022
Simple Solid primitive unit test utility.

solid-primitive-test-util Simple Solid primitive unit test utility. Install pnpm add solid-primitive-test-util -D Example Basic Usage Let's say we hav

Robert Soriano 2 Mar 21, 2022
Adds full-text search to Community Solid Server. Powered by atomic-server

Solid Search for Community Solid Server This is an extension / plugin for the Community Solid Server. It adds full-text search to the Community Solid

Ontola 4 Jun 6, 2022