Redux bindings for Firebase. Includes Higher Order Component for use with React.
Clone or download
Permalink
Failed to load latest commit information.
.github v1.4.5 (#225) Aug 8, 2017
bin fix(docs): cleanup recent fix to auth recipe including ref link - #501 Jun 27, 2018
docs fix(docs): correctly reference post from state in firebaseConnect exa… Oct 8, 2018
examples Update firestore complete example deps [ci skip] Jul 23, 2018
src fix(docs): correctly reference post from state in firebaseConnect exa… Oct 8, 2018
test Use signInAndRetrieveDataWithCustomToken as per the latest react-redu… Jun 6, 2018
.babelrc Babel module resolver added to simplify module paths in unit tests. U… Apr 29, 2018
.codeclimate.yml Fix preserving of state values. Jan 31, 2018
.eslintignore Simplify upload util. May 10, 2018
.eslintrc improved firestoreConnect to check listener results more exactly Apr 29, 2018
.gitignore Merged master. Sep 28, 2017
.istanbul.yml V0.1.8 (#43) Oct 6, 2016
.npmignore v1.5.0 (#270) Sep 18, 2017
.prettierrc Builds section added to README. Webpack version updated. .prettierrc … Feb 20, 2018
.travis.yml * fix(docs): cleanup firestore example to use correct query settings … Aug 13, 2018
CHANGELOG.md docs: react-router 4 support notes and github templates (#120) Apr 29, 2017
CNAME Gitbook docs copied from site into repo. Dec 3, 2016
CODE_OF_CONDUCT.md Version v1.2.0 (#37) Jan 23, 2017
CONTRIBUTING.md Activating Open Collective (#169) Jul 2, 2017
LICENSE.md Gitbook docs copied from site into repo. Dec 3, 2016
PATRONS.md Version v1.2.0 (#37) Jan 23, 2017
README.md fix(docs): update react-native recipe link in README.md - #527 Aug 20, 2018
SUMMARY.md Update SUMMARY.md Feb 13, 2018
book.json v2.0.0 docs updates Dec 31, 2017
codecov.yml v1.0.0 Oct 14, 2016
index.d.ts fix(typings): mark notSetValue as optional in index.d.ts - @arlair Aug 12, 2018
package-lock.json fix(typings): mark notSetValue as optional in index.d.ts Aug 12, 2018
package.json fix(typings): mark notSetValue as optional in index.d.ts Aug 12, 2018
webpack.config.js v2.0.1 (#376) Jan 16, 2018

README.md

react-redux-firebase

NPM version NPM downloads Quality Code Coverage Code Style License Build Status Dependency Status

Gitter

Redux bindings for Firebase. Includes Higher Order Component (HOC) for use with React.

Demo

The Material Example is deployed to demo.react-redux-firebase.com.

Features

  • Integrated into redux
  • Out of the box support for authentication (with auto load user profile)
  • Full Firebase Platform Support Including Real Time Database, Firestore, and Storage
  • Automatic binding/unbinding of listeners through React Higher Order Components (firebaseConnect and firestoreConnect)
  • Population capability (similar to mongoose's populate or SQL's JOIN)
  • Support small data ( using value ) or large datasets ( using child_added, child_removed, child_changed )
  • Multiple queries types supported including orderByChild, orderByKey, orderByValue, orderByPriority, limitToLast, limitToFirst, startAt, endAt, equalTo
  • Tons of examples of integrations including redux-thunk and redux-observable
  • Server Side Rendering Support
  • react-native support using native modules or web sdk

Installation

npm install --save react-redux-firebase

This assumes you are using npm as your package manager.

If you're not, you can access the library on unpkg, download it, or point your package manager to it. Theres more on this in the Builds section below.

Use

Include reactReduxFirebase (store enhancer) and firebaseReducer (reducer) while creating your redux store:

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore, combineReducers, compose } from 'redux'
import { reactReduxFirebase, firebaseReducer } from 'react-redux-firebase'
import firebase from 'firebase'
// import { reduxFirestore, firestoreReducer } from 'redux-firestore' // <- needed if using firestore
// import 'firebase/firestore' // <- needed if using firestore
// import 'firebase/functions' // <- needed if using httpsCallable

const firebaseConfig = {}

// react-redux-firebase config
const rrfConfig = {
  userProfile: 'users',
  // useFirestoreForProfile: true // Firestore for Profile instead of Realtime DB
}

// Initialize firebase instance
firebase.initializeApp(firebaseConfig)

// Initialize other services on firebase instance
// firebase.firestore() // <- needed if using firestore
// firebase.functions() // <- needed if using httpsCallable

// Add reactReduxFirebase enhancer when making store creator
const createStoreWithFirebase = compose(
  reactReduxFirebase(firebase, rrfConfig), // firebase instance as first argument
  // reduxFirestore(firebase) // <- needed if using firestore
)(createStore)

// Add firebase to reducers
const rootReducer = combineReducers({
  firebase: firebaseReducer,
  // firestore: firestoreReducer // <- needed if using firestore
})

// Create store with reducers and initial state
const initialState = {}
const store = createStoreWithFirebase(rootReducer, initialState)

// Setup react-redux so that connect HOC can be used
const App = () => (
  <Provider store={store}>
    <Todos />
  </Provider>
);

render(<App/>, document.getElementById('root'));

The Firebase instance can then be grabbed from context within your components (withFirebase and firebaseConnect Higher Order Components provided to help):

Add Data

import React from 'react'
import PropTypes from 'prop-types'
import { withFirebase } from 'react-redux-firebase'

const Todos = ({ firebase }) => {
  const sampleTodo = { text: 'Sample', done: false }
  const pushSample = () => firebase.push('todos', sampleTodo)
  return (
    <div>
      <h1>Todos</h1>
      <ul>
        {todosList}
      </ul>
      <input type="text" ref="newTodo" />
      <button onClick={pushSample}>
        Add
      </button>
    </div>
  )
}

export default withFirebase(Todos)
// or firebaseConnect()(Todos)

Load Data (listeners automatically managed on mount/unmount)

import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { compose } from 'redux'
import { firebaseConnect, isLoaded, isEmpty } from 'react-redux-firebase'

const Todos = ({ todos, firebase }) => {
  // Build Todos list if todos exist and are loaded
  const todosList = !isLoaded(todos)
    ? 'Loading'
    : isEmpty(todos)
      ? 'Todo list is empty'
      : Object.keys(todos).map(
          (key, id) => (
            <TodoItem key={key} id={id} todo={todos[key]}/>
          )
        )
  return (
    <div>
      <h1>Todos</h1>
      <ul>
        {todosList}
      </ul>
      <input type="text" ref="newTodo" />
      <button onClick={this.handleAdd}>
        Add
      </button>
    </div>
  )
}

export default compose(
  firebaseConnect([
    'todos' // { path: '/todos' } // object notation
  ]),
  connect((state) => ({
    todos: state.firebase.data.todos,
    // profile: state.firebase.profile // load profile
  }))
)(Todos)

Queries Based On Props

It is common to make a detail page that loads a single item instead of a whole list of items. A query for a specific Todos can be created using

import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { compose } from 'redux'
import { firebaseConnect, getVal } from 'react-redux-firebase'

// Component enhancer that loads todo into redux then into the todo prop
const enhance = compose(
  firebaseConnect((props) => {
    // Set listeners based on props (prop is route parameter from react-router in this case)
    return [
      { path: `todos/${props.params.todoId}` }, // create todo listener
      // `todos/${props.params.todoId}` // equivalent string notation
    ]
  }),
  connect(({ firebase }, props) => ({
    todo: getVal(firebase, `data/todos/${props.params.todoId}`), // lodash's get can also be used
  }))
)

const Todo = ({ todo, firebase, params }) =>
  <div>
    <input
      name="isDone"
      type="checkbox"
      checked={todo.isDone}
      onChange={() =>
        firebase.update(`todos/${params.todoId}`, { done: !todo.isDone })
      }
    />
    <span>{todo.label}</span>
  </div>

// Export enhanced component
export default enhance(Todo)

Load Data On Click

import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { compose } from 'redux'
import { withFirebase, isLoaded, isEmpty } from 'react-redux-firebase'

const Todos = ({ firebase }) => {
  // Build Todos list if todos exist and are loaded
  const todosList = !isLoaded(todos)
    ? 'Loading'
    : isEmpty(todos)
      ? 'Todo list is empty'
      : Object.keys(todos).map(
          (key, id) => <TodoItem key={key} id={id} todo={todos[key]}/>
        )
  return (
    <div>
      <h1>Todos</h1>
      <ul>
        {todosList}
      </ul>
      <button onClick={() => firebase.watchEvent('value', 'todos')}>
        Load Todos
      </button>
    </div>
  )
}

// Export enhanced component
export default compose(
  withFirebase, // or firebaseConnect()
  connect((state) => ({
    todos: state.firebase.data.todos,
    // profile: state.firebase.profile // load profile
  }))
)(Todos)

Firestore

If you plan to use Firestore, you should checkout redux-firestore. It integrates nicely with react-redux-firebase and it allows you to run Real Time Database and Firestore along side each other.

react-redux-firebase provides the firestoreConnect HOC (similar to firebaseConnect) for easy setting/unsetting of listeners.

Currently react-redux-firebase still handles auth when using redux-firestore - The future plan is to also have auth standalone auth library that will allow the developer to choose which pieces they do/do not want.

Docs

See full documentation at react-redux-firebase.com

Examples

Real World Applications

If you would like a project added to this section please reach out over gitter

Examples Folder

Examples folder is broken into two categories snippets and complete. /complete contains full applications that can be run as is, where as /snippets contains small amounts of code to highlight specific functionality (dev tools and deps not included).

State Based Query Snippet

Snippet showing querying based on data in redux state. One of the more common examples is querying based on the current users auth UID.

Decorators Snippet

Snippet showing how to use decorators to simplify connect functions (redux's connect and react-redux-firebase's firebaseConnect)

Simple App Example

A simple example that was created using create-react-app's. Shows a list of todo items and allows you to add to them.

Material App Example

An example that user Material UI built on top of the output of create-react-app's eject command. Shows a list of todo items and allows you to add to them. This is what is deployed to redux-firebasev3.firebaseapp.com.

Discussion

Join us on the redux-firebase gitter.

Integrations

View docs for recipes on integrations with:

Starting A Project

Generator

generator-react-firebase is a yeoman generator uses react-redux-firebase when opting to include redux.

Complete Examples

The examples folder contains full applications that can be copied/adapted and used as a new project.

FAQ

Please visit the FAQ section of the docs

Builds

Most commonly people consume Redux Firestore as a CommonJS module. This module is what you get when you import redux in a Webpack, Browserify, or a Node environment.

If you don't use a module bundler, it's also fine. The redux-firestore npm package includes precompiled production and development UMD builds in the dist folder. They can be used directly without a bundler and are thus compatible with many popular JavaScript module loaders and environments. For example, you can drop a UMD build as a <script> tag on the page. The UMD builds make Redux Firestore available as a window.ReduxFirestore global variable.

It can be imported like so:

<script src="../node_modules/react-redux-firebase/dist/react-redux-firebase.min.js"></script>
<!-- or through cdn: <script src="https://unpkg.com/react-redux-firebase@latest/dist/react-redux-firebase.min.js"></script> -->
<script>console.log('react redux firebase:', window.ReactReduxFirebase)</script>

Note: In an effort to keep things simple, the wording from this explanation was modeled after the installation section of the Redux Docs.

Contributors

This project exists thanks to all the people who contribute.

Backers

Thank you to all our backers! 🙏