Giter VIP home page Giter VIP logo

react-redux-firebase's Introduction

react-redux-firebase

NPM version NPM downloads Quality Code Coverage Code Style License Build Status Dependency Status Backers on Open Collective

Gitter

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

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

Features

  • Integrated into redux
  • Support for updating and nested props
  • Population capability (similar to mongoose's populate or SQL's JOIN)
  • Out of the box support for authentication (with auto load user profile)
  • Firebase Storage Support
  • Support small data ( using value ) or large datasets ( using child_added, child_removed, child_changed )
  • queries support ( orderByChild, orderByKey, orderByValue, orderByPriority, limitToLast, limitToFirst, startAt, endAt, equalTo right now )
  • Automatic binding/unbinding
  • Declarative decorator syntax for React components
  • Tons of integrations including redux-thunk and redux-observable
  • Action Types and other Constants exported for external use (such as in redux-observable)
  • Firebase v3+ support
  • Server Side Rendering Support
  • react-native support using native modules or web sdk

Install

npm install --save react-redux-firebase

Other Versions

The above install command will install the @latest tag. You may also use the following tags when installing to get different versions:

  • @next - Next upcoming release. currently points to active progress with v1.5.0-* pre-releases
  • @canary - Most possible up to date code. Currently points to active progress with v2.0.0-* pre-releases. Warning: Syntax is different than current stable version.

Other versions docs are available using the dropdown on the above docs link. For quick access:

Note: Be aware of changes when using version that are tagged @latest. Please report any issues you encounter, and try to keep an eye on the releases page for relevant release info.

Use

NOTE: If you are just starting a new project, you might want to use v2.0.0 has an even easier syntax. For clarity on the transition, view the v1 -> v2 migration guide

Include reactReduxFirebase in your store compose function and firebaseStateReducer in your reducers:

import { createStore, combineReducers, compose } from 'redux'
import { reactReduxFirebase, firebaseStateReducer } from 'react-redux-firebase'

// Add Firebase to reducers
const rootReducer = combineReducers({
  firebase: firebaseStateReducer
})

// Firebase config
const config = {
  apiKey: '<your-api-key>',
  authDomain: '<your-auth-domain>',
  databaseURL: '<your-database-url>',
  storageBucket: '<your-storage-bucket>'
}

// Add redux Firebase to compose
const createStoreWithFirebase = compose(
  reactReduxFirebase(config, { userProfile: 'users' }),
)(createStore)

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

In components:

import React, { Component } from 'react'
import PropTypes from 'prop-types' // can also come from react if react <= 15.4.0
import { connect } from 'react-redux'
import { compose } from 'redux'
import {
  firebaseConnect,
  isLoaded,
  isEmpty,
  dataToJS,
  pathToJS
} from 'react-redux-firebase'

class Todos extends Component {
  static propTypes = {
    todos: PropTypes.object,
    auth: PropTypes.object,
    firebase: PropTypes.object
  }

  addTodo = () => {
    const { newTodo } = this.refs
    return this.props.firebase
      .push('/todos', { text: newTodo.value, done: false })
      .then(() => {
        newTodo.value = ''
        console.log('Todo Created!')
      })
      .catch((err) => {
        console.log('Error creating todo:', err) // error is also set to authError
      })
  }

  render() {
    const { todos } = this.props;

    // 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(
    ({ firebase } }) => ({ // state.firebase
      todos: dataToJS(firebase, 'todos'), // in v2 todos: firebase.data.todos
      auth: pathToJS(firebase, 'auth') // in v2 todos: firebase.auth
    })
  )
)(Todos)

Alternatively, if you choose to use decorators:

@firebaseConnect([
  'todos' // { path: 'todos' } // object notation
])
@connect(
  ({ firebase }) => ({
    todos: dataToJS(firebase, 'todos'), // in v2 todos: firebase.data.todos
    auth: pathToJS(firebase, 'auth') // in v2 todos: firebase.auth
  })
)
export default class Todos extends Component {

}

Decorators

Though they are optional, it is highly recommended that you use decorators with this library. The Simple Example shows implementation without decorators, while the Decorators Example shows the same application with decorators implemented.

A side by side comparison using react-redux's connect function/HOC is the best way to illustrate the difference:

Without Decorators

class SomeComponent extends Component {

}
export default connect()(SomeComponent)

vs.

With Decorators

@connect()
export default class SomeComponent extends Component {

}

In order to enable this functionality, you will most likely need to install a plugin (depending on your build setup). For Webpack and Babel, you will need to make sure you have installed and enabled babel-plugin-transform-decorators-legacy by doing the following:

  1. run npm i --save-dev babel-plugin-transform-decorators-legacy
  2. Add the following line to your .babelrc:
{
  "plugins": ["transform-decorators-legacy"]
}

See full documentation at react-redux-firebase.com

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

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

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

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

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

  1. How is this different than redux-react-firebase?

This library was actually originally forked from redux-react-firebase, but adds extended functionality such as:

Well why not combine?

I have been talking to the author of redux-react-firebase about combining, but we are not sure that the users of both want that at this point. Join us on the redux-firebase gitter if you haven't already since a ton of this type of discussion goes on there.

  1. Why use redux if I have Firebase to store state?

This isn't a super quick answer, so I wrote up a medium article to explain

  1. Where can I find some examples?
  1. How does connect relate to firebaseConnect?

data flow

  1. How do I help?
  • Join the conversion on gitter
  • Post Issues
  • Create Pull Requests

Contributors

This project exists thanks to all the people who contribute.

Backers

Thank you to all our backers! ๐Ÿ™

react-redux-firebase's People

Contributors

biomorgoth avatar bojhan avatar davidmdem avatar emilguareno avatar fgeo23 avatar iamjoshellis avatar imarian97 avatar itwasmattgregg avatar jonvuri avatar justinhandley avatar justintulloss avatar lulalachen avatar mariushab avatar mrshll avatar mutewinter avatar prescottprue avatar rahavlussato avatar theghoul21 avatar timkindberg avatar tushardhoot avatar xdamman avatar

Watchers

 avatar  avatar

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.