How to use firebase - 10 common examples

To help you get started, we’ve selected a few firebase examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github flow-typed / flow-typed / definitions / npm / firebase_v4.x.x / flow_v0.34.x-v0.45.x / test_firebase.js View on Github external
// @flow

import firebase from 'firebase';
import app from 'firebase/app';
import auth from 'firebase/auth';
import database from 'firebase/database';

// #1
const a1: firebase.app.App = firebase.initializeApp({
  apiKey: 'apiKey',
  databaseURL: 'databaseURL',
  projectId: '42',
});

// #2
// $ExpectError
const a2: firebase.app.App = firebase.initializeApp({
  storageBucker: 'storageBucket',
  projectId: '42',
});

// #3
const a3: app.App = app('DEFAULT');

// #4
github jsayol / FireSQL / tools / test-data / test-setup.ts View on Github external
JSON.stringify(config, null, 2)
    );

    // Deploy database rules
    task = showTask('Deploying Firestore indexes and security rules');
    await firebaseTools.deploy({
      project,
      token,
      cwd: resolvePath(__dirname, '../../config')
    });

    // Firestore calls grpc.load() which has been deprecated and we
    // get an ugly warning on screen. This mutes it temporarily.
    const unmute = muteDeprecationWarning();

    const firestore = firebase.initializeApp(config).firestore();
    firestore.settings({ timestampsInSnapshots: true });
    const rootRef = firestore.doc('/');

    task = showTask('Deleting "shops" collection');
    await firebaseTools.firestore.delete('/shops', {
      project,
      yes: true,
      recursive: true
    });

    task = showTask('Loading test data into "shops" collection');
    await loadTestDataset(rootRef, loadJSONFile(
      './data.json'
    ) as TestCollection[]);

    unmute();
github flow-typed / flow-typed / definitions / npm / firebase_v5.x.x / flow_v0.104.x- / test_firebase.js View on Github external
// #31
firebase
  .firestore()
  .collection('/foo')
  .where('id', '==', '5')
  .get({ source: 'cache' });

// #32
firebase
 .firestore()
 .collection('/foo')
 .where('id', 'array-contains', '5')
 .get({ source: 'cache' });

// #33
firebase
 .firestore()
 .collection('/foo')
 // $ExpectError
 .where('id', 'lte', '5')
 .get({ source: 'cache' });

// #34
firebase
  .firestore()
  .collection('/foo')
  .add({foo: 'bar'})
  .then(document => {
    const id = document.id
  })

// #35
github zeit / next.js / examples / z-experimental-next-news / lib / db.js View on Github external
import firebase from 'firebase'

try {
  firebase.initializeApp({
    databaseURL: 'https://hacker-news.firebaseio.com',
  })
} catch (err) {
  // we skip the "already exists" message which is
  // not an actual error when we're hot-reloading
  if (!/already exists/.test(err.message)) {
    console.error('Firebase initialization error', err.stack)
  }
}

const root = firebase.database().ref('v0')

export default root
github saltycrane / kage / lib / firebase.js View on Github external
/* @flow */
import firebase from "firebase/app";
import "firebase/auth";

try {
  firebase.initializeApp({
    apiKey: "AIzaSyDYXNe8SruSoEgaWWXyiIgZmGBm2xCleQ4",
    authDomain: "kage-e9d8c.firebaseapp.com",
    databaseURL: "https://kage-e9d8c.firebaseio.com",
  });
} catch (err) {
  // taken from https://github.com/now-examples/next-news/blob/master/lib/db.js
  if (!/already exists/.test(err.message)) {
    console.error("Firebase initialization error", err.stack);
  }
}

/**
 * Firebase auth functions. They return a promise.
 */
export function linkAnonymousUser(email: string, password: string) {
  const user = firebase.auth().currentUser;
github IjzerenHein / firestorter / examples / importCSV / index.js View on Github external
company: row[0].trim(),
			origin: row[1].trim(),
			reviewDate: new Date(Number(row[3]), 1, 1, 0, 0, 0, 0),
			cocaoPercent: Number(row[4].substring(0, row[4].length - 1)) / 100,
			companyLocation: row[5].trim(),
			rating: Number(row[6]),
			beanType: row[7].trim(),
			broadBeanOrigin: row[8].trim(),
			location: new firebase.firestore.GeoPoint(latitude, longitude),
			geohash: encodeGeohash({
				latitude,
				longitude
			})
		};
		// console.info('Adding ' + i + ' of ' + count + ': ' + row);
		const ref = firebase.firestore().doc('chocolateBars/' + id);
		writeBatch.set(ref, json);
	}
	await writeBatch.commit();
	console.timeEnd('import');
}
github hammer-io / yggdrasil / src / actions / session.js View on Github external
return async (dispatch) => {
    try {
      const fetchClient = new FetchClient()
      fetchClient.setAuthToken(token)
      // This endpoint doesn't return anything upon success (result is always null)
      // eslint-disable-next-line no-unused-vars
      const { result, error } = await fetchClient.delete({
        url: '/auth/logout'
      })
      if (!error) {
        dispatch(setAccessToken(null))
        dispatch(setUser(null))
        await firebase.auth().signOut()
        return
      }

      console.error(error)
      return { result: null, error }
    } catch (error) {
      logError(dispatch, error)
      return error
    }
  }
}
github andrewjmead / react-course-2-expensify-app / src / firebase / firebase.js View on Github external
import * as firebase from 'firebase';

const config = {
  apiKey: process.env.FIREBASE_API_KEY,
  authDomain: process.env.FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.FIREBASE_DATABASE_URL,
  projectId: process.env.FIREBASE_PROJECT_ID,
  storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID
};

firebase.initializeApp(config);

const database = firebase.database();
const googleAuthProvider = new firebase.auth.GoogleAuthProvider();

export { firebase, googleAuthProvider, database as default };

// // child_removed
// database.ref('expenses').on('child_removed', (snapshot) => {
//   console.log(snapshot.key, snapshot.val());
// });

// // child_changed
// database.ref('expenses').on('child_changed', (snapshot) => {
//   console.log(snapshot.key, snapshot.val());
// });
github isamu / FriendlyEats-React / src / App.js View on Github external
import React, { useState, useEffect } from 'react';
import { Route, BrowserRouter as Router } from 'react-router-dom';
import CssBaseline from '@material-ui/core/CssBaseline';
import MuiThemeProvider from '@material-ui/core/styles/MuiThemeProvider';
import theme from './theme';
import Home from './Home';
import About from './About';
import ErrorModal from './ErrorModal';
import Restaurant from './Restaurant';
import * as firebase from "firebase/app";
import "firebase/firestore";
import "firebase/auth";
import config from './config';

try {
  firebase.initializeApp(config);
} catch (e) {
  // console.log(firebase init error)
}

function App() {
  const [errorModalOpen, setErrorModalOpen ] = useState(false);
  const [errorType, setErrorType ] = useState("");
  
  useEffect(()=>{
    const init = async () => {
      if (!config || Object.keys(config).length === 0) {
        setErrorType("app.config");
        setErrorModalOpen(true);
      } else {
        try {
          await firebase.auth().signInAnonymously();
github FirebaseExtended / firebase-auth-service-worker-sessions / src / script.js View on Github external
// Registration failed.
        console.log('Registration failed with ' + error.message);
      });
} else {
  window.location.assign('/unsupported');
}

/**
 * Initializes the app.
 */
const initApp = () => {
  // Renders sign-in page using FirebaseUI.
  ui.start('#firebaseui-container', getUiConfig());
};
// Initialize Firebase app.
var app = firebase.initializeApp(config);
// Set persistence to local.
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL);
// Initialize the FirebaseUI Widget using Firebase.
const ui = new firebaseui.auth.AuthUI(app.auth());
// On page ready, initialize app.
window.addEventListener('load', initApp);