Giter VIP home page Giter VIP logo

solid-firebase's Introduction

solid-firebase

solid-firebase

Solid primitives for Firebase.

⚠️ This package only works with Firebase 9 or above with modular style.

Quick start

Install it:

npm install firebase solid-firebase

Configure firebase app:

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

const app = initializeApp({ projectId: 'MY PROJECT ID' })

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

Primitives

The primitive useFirebaseApp gives you access to the initialized firebase app.

Authentication

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

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

function Login() {
  const app = useFirebaseApp()
  const signIn = () => signInWithPopup(getAuth(app), new GoogleAuthProvider())

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

function App() {
  const app = useFirebaseApp()
  const state = useAuth(getAuth(app))

  return (
    <Switch fallback={<Login />}>
      <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, createMemo, createSignal } from 'solid-js'
import { collection, getFirestore, limit, orderBy } from 'firebase/firestore'
import { useFirebaseApp, useFirestore } from 'solid-firebase'

function App() {
  const app = useFirebaseApp()
  const db = getFirestore(app)
  const todos = useFirestore(collection(db, 'todos'))

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

  // you can also use an accessor for reactive query
  const [postsLimit] = createSignal(10)
  const postsQuery = createMemo(() => query(
    collection(db, 'posts'),
    orderBy('createdAt', 'desc'),
    limit(postsLimit())
  ))
  const posts = useFirestore(postsQuery)

  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, useFirebaseApp } from 'solid-firebase'

function App() {
  const app = useFirebaseApp()
  const db = getDatabase(app)
  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, useFirebaseApp } from 'solid-firebase'

function App() {
  const app = useFirebaseApp()
  const storage = getStorage(app)
  const data = useDownloadURL(ref(
    storage,
    'images/yourimage.jpg',
  ))

  // or with an accessor
  const [location] = createSignal('images/yourimage.jpg')
  const downloadRef = createMemo(() => ref(storage, location()))
  const data = useDownloadURL(downloadRef)

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

License

MIT

solid-firebase's People

Contributors

tycrimm avatar wobsoriano avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

solid-firebase's Issues

Solving server-side access to values

@wobsoriano I was curious if you had any thoughts about making it easy to use the primitives in a server-side setting. I'm using solid-firebase with Start and would love to use the same primitives isomorphically. Any suggestions or thoughts on how it might be possible? I'm new to Firebase API itself.

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

Component auth has not been registered yet

When copying code from tutorial in the readme, I get this error when accessing my app. Only changes I've made is adding in my firebase config, everything else is as written in the readme.

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 😬❤️

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

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;

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)]
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.