firebase-redux
Utility functions to connect your Firebase realtime database with a Redux store. This library was written to accompany the Medium article: https://medium.com/@aakashns/575f8294332d
It provides utility functions linkStoreWithPath
, linkStoreWithChildren
and linkStoreWithDb
to set up two-way bindings between portions of the Firebase realtime database and a Redux store.
Installation
Install using npm
or yarn
:
npm install firebase-redux --save
or
yarn add firebase-redux
Usage
linkStoreWithPath(path, actionCreator, selector)
Set up a two way binding between the realtime database and the Redux store. path
specifies the location in the database that is bound, and actionCreator
and selector
specify how the Redux store should be written to and read from.
Example
; // The database path you want to bind withconst messagePath = '/message' // Action to dispatch when the value in the database changesconst messageActionCreator = type: 'SET_MESSAGE' payload: message; // Portion of the state that should be written to the databaseconst messageSelector = statemessage; // Create a function to bind '/message' in the database// with 'state.message' in the Redux storeconst linkMessage = ; // Invoke anywhere in the code to set up the bindingconst unlink = ; // Invoke unlink to remove the binding;
linkStoreWithDb(fromDb, fromStore)(database, store)
Set up a custom binding between a Firebase realtime datbase instance and a Redux store. linkStoreWithPath
uses linkStoreWithDb
internally.
Example
; // Set up a two way binding between '/message' in the // database and 'store.state' in the Redux storeconst linkMessage = { // Keep track of the previous state let previous = store; // Whether or not to write to the database let mustWrite = true; const fromDb = { const listener = db; // Return a method to stop listening for database changes return db; }; const fromStore = { // Get the portion of the state we care about const portion = statemessage; // Check if we need to write to the database if mustWrite && portion !== previous // Write to the datbase db; // Update the previous state previous = portion; }; // Use linkStoreWithDb to tie it all together. return db store;}; // Invoke anywhere in the code to set up the bindingconst unlink = ; // Invoke unlink to remove the binding;