Repository files navigation

re-base

Build StatusCoverage Status

welcome

Questions? Find me on twitter at @tylermcginnis33

What is re-base?

React.js makes managing state easy to reason about. Firebase makes persisting your data easy to implement. re-base, inspired by Relay, combines the benefits of React and Firebase by allowing each component to specify its own data dependency. Forget about your data persistence and focus on what really matters, your application's state.

Why re-base?

I spent a few weeks trying to figure out the cleanest way to implement Firebase into my React/Flux application. After struggling for a bit, I tweeted my frustrations. I was enlightened to the fact that Firebase and Flux really don't work well together. It makes sense why they don't work together, because they're both trying to accomplish roughly the same thing. So I did away with my reliance upon Flux and tried to think of a clean way to implement React with Firebase. I came across ReactFire built by Jacob Wenger at Firebase and loved his idea. Sync a Firebase endpoint with a property on your component's state. So whenever your data changes, your state will be updated. Simple as that. The problem with ReactFire is because it uses Mixins, it's not compatible with ES6 classes. After chatting with Jacob Turner, we wanted to create a way to allow the one way binding of ReactFire with ES6 classes along some more features like two way data binding and listening to Firebase endpoints without actually binding a state property to them. Thus, re-base was built.

Features

  • syncState: Two way data binding between any property on your component's state and any endpoint in Firebase. Use the same API you're used to to update your component's state (setState), and Firebase will also update.
  • bindToState: One way data binding. Whenever your Firebase endpoint changes, the property on your state will update as well.
  • listenTo: Whenever your Firebase endpoint changes, it will invoke a callback passing it the new data from Firebase.
  • fetch: Retrieve data from Firebase without setting up any binding or listeners.
  • post: Add new data to Firebase.
  • push: Push new child data to Firebase.
  • removeBinding: Remove all of the Firebase listeners when your component unmounts.
  • reset: Removes all of the Firebase listeners and resets the singleton (for testing purposes).

Installing

$ npm install re-base

API

For more in depth examples of the API, see the examples folder.

createClass(firebaseUrl)

Purpose

Accepts a firebase URL as its only parameter and returns a singleton with the re-base API.

Arguments
  1. firebaseUrl:
    • type: string
    • The absolute, HTTPS URL of your Firebase project
Return Value

An object with syncState, bindToState, listenTo, fetch, post, push, removeBinding, and reset methods.

Example
varRebase=require('re-base');varbase=Rebase.createClass('https://myapp.firebaseio.com');

syncState(endpoint, options)

Purpose

Allows you to set up two way data binding between your component's state and your Firebase. Whenever your Firebase changes, your component's state will change. Whenever your component's state changes, Firebase will change.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint to which you'd like to bind your component's state
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • state: (string - required) The state property you want to sync with Firebase
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.
    • then: (function - optional) The callback function that will be invoked when the initial listener is established with Firebase. Typically used (with syncState) to change this.state.loading to false.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.syncState(`shoppingList`,{context: this,state: 'items',asArray: true});}addItem(newItem){this.setState({items: this.state.items.concat([newItem])//updates Firebase and the local state});}

bindToState(endpoint, options)

Purpose

One way data binding from Firebase to your component's state. Allows you to bind a component's state property to a Firebase endpoint so whenever that Firebase endpoint changes, your component's state will be updated with that change.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like your component's state property to listen for changes
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • state: (string - required) The state property you want to sync with Firebase
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.bindToState('tasks',{context: this,state: 'tasks',asArray: true});}

listenTo(endpoint, options)

Purpose

Allows you to listen to Firebase endpoints without binding those changes to a state property. Instead, a callback will be invoked with the newly updated data.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint which contains the data with which you'd like to invoke your callback function
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • then: (function - required) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.listenTo('votes',{context: this,asArray: true,then(votesData){vartotal=0;votesData.forEach((vote,index)=>{total+=vote});this.setState({total});}})}

fetch(endpoint, options)

Purpose

Allows you to retrieve the data from a Firebase endpoint just once without subscribing or listening for data changes.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint which contains the data you're wanting to fetch
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • then: (function - required) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

No return value

Example

getSales(){base.fetch('sales',{context: this,asArray: true,then(data){console.log(data);}});}

post(endpoint, options)

Purpose

Allows you to update a Firebase endpoint with new data. Replace all the data at this endpoint with the new data

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like to update with the new data
  2. options - type: object - properties:
    • data: (any - required) The data you're wanting to persist to Firebase
    • then: (function - optional) A callback that will get invoked once the new data has been saved to Firebase

Return Value

No return value

Example

addUser(){base.post(`users/${userId}`,{data: {name: 'Tyler McGinnis',age: 25},then(){Router.transitionTo('dashboard');}});}

push(endpoint, options)

Purpose

Allows you to add data to a Firebase endpoint. Adds data to a child of the endpoint with a new Firebase push key

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like to push the new data to
  2. options - type: object - properties:
    • data: (any - required) The data you're wanting to persist to Firebase
    • then: (function - optional) A callback that will get invoked once the new data has been saved to Firebase

Return Value

A Firebase reference for the generated location

Example

addBear(){base.push('bears',{data: {name: 'George',type: 'Grizzly'},then(){Router.transitionTo('dashboard');}});}

removeBinding(ref)

Purpose

Remove the listeners to Firebase when your component unmounts.

Arguments

  1. ref - type: Object - The return value of syncState, bindToState, or listenTo

Return Value

No return value

Example

componentDidMount(){this.ref=base.syncState('users',{context: this,state: 'users'});}componentWillUnmount(){base.removeBinding(this.ref);}

reset()

Purpose

Removes every Firebase listener and resets all private variables. Used for testing purposes.

Arguments

No Arguments

Return Value

No return value


Use the query option to utilize the Firebase Query API. For a list of available queries and how they work, see the Firebase docs.

Queries are accepted in the options object of each read method (syncState, bindToState, listenTo, and fetch). The object should have one or more keys of the type of query you wish to run, with the value being the value for the query. For example:

base.syncState('users',{context: this,state: 'users',asArray: true,queries: {orderByChild: 'iq',limitToLast: 3}})

The binding above will sort the users endpoint by iq, retrieve the last three (or, three with highest iq), and bind it to the component's users state. NOTE: This query is happening within Firebase. The only data that will be retrieved are the three users with the highest iq.

re-base exposes Firebase's web clientauthWithPassword, authWithCustomToken, authWithOAuthPopup, authWithOAuthRedirect, authWithOAuthToken methods to allow user authentication. getAuth is also exposed to access the current authentication state.

// Simple email authenticationbase.authWithPassword({email : 'bobtony@firebase.com',password : 'correcthorsebatterystaple'},authHandler);// Authentication via a custom authentication tokenbase.authWithCustomToken(token,authHandler);// Authentication via OAuth providers ("facebook", "github", "google", or "twitter")base.authWithOAuthPopup("<provider>",authHandler);base.authWithOAuthRedirect("<provider>",authHandler);base.authWithOAuthToken("<provider>",token,authHandler);// Log a user outbase.unauth()// Get authentication informationvarauthData=base.getAuth();
// Listen to authenticationfunctionauthDataCallback(authData){if(authData){console.log("User "+authData.uid+" is logged in with "+authData.provider);}else{console.log("User is logged out");}}varref=newFirebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");ref.onAuth(authDataCallback);

re-base exposes createUser, removeUser, resetPassword and changePassword methods for user management.

// Createbase.createUser({email: 'bobtony@firebase.com',password: 'correcthorsebatterystaple'},userHandler);// Removebase.removeUser({email: 'bobtony@firebase.com',password: 'correcthorsebatterystaple'},errorHandler);// Reset Passwordbase.resetPassword({email: 'bobtony@firebase.com'},errorHandler);// Change Passwordbase.changePassword({email: 'bobtony@firebase.com',oldPassword: 'correcthorsebatterystaple',newPassword: 'chipsahoy'},errorHandler);

Contributing

  1. npm install
  2. Edit src/rebase.js
  3. Add/edit tests in tests/specs/re-base.spec.js
  4. npm run build
  5. npm run test

Credits

re-base is inspired by ReactFire from Firebase. Jacob Turner is also a core contributor and this wouldn't have been possible without his assistance.

License

MIT

About

🔥 A Relay inspired library for building React.js + Firebase applications. 🔥

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

re-base

Build StatusCoverage Status

welcome

Questions? Find me on twitter at @tylermcginnis33

What is re-base?

React.js makes managing state easy to reason about. Firebase makes persisting your data easy to implement. re-base, inspired by Relay, combines the benefits of React and Firebase by allowing each component to specify its own data dependency. Forget about your data persistence and focus on what really matters, your application's state.

Why re-base?

I spent a few weeks trying to figure out the cleanest way to implement Firebase into my React/Flux application. After struggling for a bit, I tweeted my frustrations. I was enlightened to the fact that Firebase and Flux really don't work well together. It makes sense why they don't work together, because they're both trying to accomplish roughly the same thing. So I did away with my reliance upon Flux and tried to think of a clean way to implement React with Firebase. I came across ReactFire built by Jacob Wenger at Firebase and loved his idea. Sync a Firebase endpoint with a property on your component's state. So whenever your data changes, your state will be updated. Simple as that. The problem with ReactFire is because it uses Mixins, it's not compatible with ES6 classes. After chatting with Jacob Turner, we wanted to create a way to allow the one way binding of ReactFire with ES6 classes along some more features like two way data binding and listening to Firebase endpoints without actually binding a state property to them. Thus, re-base was built.

Features

  • syncState: Two way data binding between any property on your component's state and any endpoint in Firebase. Use the same API you're used to to update your component's state (setState), and Firebase will also update.
  • bindToState: One way data binding. Whenever your Firebase endpoint changes, the property on your state will update as well.
  • listenTo: Whenever your Firebase endpoint changes, it will invoke a callback passing it the new data from Firebase.
  • fetch: Retrieve data from Firebase without setting up any binding or listeners.
  • post: Add new data to Firebase.
  • push: Push new child data to Firebase.
  • removeBinding: Remove all of the Firebase listeners when your component unmounts.
  • reset: Removes all of the Firebase listeners and resets the singleton (for testing purposes).

Installing

$ npm install re-base

API

For more in depth examples of the API, see the examples folder.

createClass(firebaseUrl)

Purpose

Accepts a firebase URL as its only parameter and returns a singleton with the re-base API.

Arguments
  1. firebaseUrl:
    • type: string
    • The absolute, HTTPS URL of your Firebase project
Return Value

An object with syncState, bindToState, listenTo, fetch, post, push, removeBinding, and reset methods.

Example
varRebase=require('re-base');varbase=Rebase.createClass('https://myapp.firebaseio.com');

syncState(endpoint, options)

Purpose

Allows you to set up two way data binding between your component's state and your Firebase. Whenever your Firebase changes, your component's state will change. Whenever your component's state changes, Firebase will change.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint to which you'd like to bind your component's state
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • state: (string - required) The state property you want to sync with Firebase
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.
    • then: (function - optional) The callback function that will be invoked when the initial listener is established with Firebase. Typically used (with syncState) to change this.state.loading to false.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.syncState(`shoppingList`,{context: this,state: 'items',asArray: true});}addItem(newItem){this.setState({items: this.state.items.concat([newItem])//updates Firebase and the local state});}

bindToState(endpoint, options)

Purpose

One way data binding from Firebase to your component's state. Allows you to bind a component's state property to a Firebase endpoint so whenever that Firebase endpoint changes, your component's state will be updated with that change.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like your component's state property to listen for changes
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • state: (string - required) The state property you want to sync with Firebase
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.bindToState('tasks',{context: this,state: 'tasks',asArray: true});}

listenTo(endpoint, options)

Purpose

Allows you to listen to Firebase endpoints without binding those changes to a state property. Instead, a callback will be invoked with the newly updated data.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint which contains the data with which you'd like to invoke your callback function
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • then: (function - required) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.listenTo('votes',{context: this,asArray: true,then(votesData){vartotal=0;votesData.forEach((vote,index)=>{total+=vote});this.setState({total});}})}

fetch(endpoint, options)

Purpose

Allows you to retrieve the data from a Firebase endpoint just once without subscribing or listening for data changes.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint which contains the data you're wanting to fetch
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • then: (function - required) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

No return value

Example

getSales(){base.fetch('sales',{context: this,asArray: true,then(data){console.log(data);}});}

post(endpoint, options)

Purpose

Allows you to update a Firebase endpoint with new data. Replace all the data at this endpoint with the new data

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like to update with the new data
  2. options - type: object - properties:
    • data: (any - required) The data you're wanting to persist to Firebase
    • then: (function - optional) A callback that will get invoked once the new data has been saved to Firebase

Return Value

No return value

Example

addUser(){base.post(`users/${userId}`,{data: {name: 'Tyler McGinnis',age: 25},then(){Router.transitionTo('dashboard');}});}

push(endpoint, options)

Purpose

Allows you to add data to a Firebase endpoint. Adds data to a child of the endpoint with a new Firebase push key

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like to push the new data to
  2. options - type: object - properties:
    • data: (any - required) The data you're wanting to persist to Firebase
    • then: (function - optional) A callback that will get invoked once the new data has been saved to Firebase

Return Value

A Firebase reference for the generated location

Example

addBear(){base.push('bears',{data: {name: 'George',type: 'Grizzly'},then(){Router.transitionTo('dashboard');}});}

removeBinding(ref)

Purpose

Remove the listeners to Firebase when your component unmounts.

Arguments

  1. ref - type: Object - The return value of syncState, bindToState, or listenTo

Return Value

No return value

Example

componentDidMount(){this.ref=base.syncState('users',{context: this,state: 'users'});}componentWillUnmount(){base.removeBinding(this.ref);}

reset()

Purpose

Removes every Firebase listener and resets all private variables. Used for testing purposes.

Arguments

No Arguments

Return Value

No return value


Use the query option to utilize the Firebase Query API. For a list of available queries and how they work, see the Firebase docs.

Queries are accepted in the options object of each read method (syncState, bindToState, listenTo, and fetch). The object should have one or more keys of the type of query you wish to run, with the value being the value for the query. For example:

base.syncState('users',{context: this,state: 'users',asArray: true,queries: {orderByChild: 'iq',limitToLast: 3}})

The binding above will sort the users endpoint by iq, retrieve the last three (or, three with highest iq), and bind it to the component's users state. NOTE: This query is happening within Firebase. The only data that will be retrieved are the three users with the highest iq.

re-base exposes Firebase's web clientauthWithPassword, authWithCustomToken, authWithOAuthPopup, authWithOAuthRedirect, authWithOAuthToken methods to allow user authentication. getAuth is also exposed to access the current authentication state.

// Simple email authenticationbase.authWithPassword({email : 'bobtony@firebase.com',password : 'correcthorsebatterystaple'},authHandler);// Authentication via a custom authentication tokenbase.authWithCustomToken(token,authHandler);// Authentication via OAuth providers ("facebook", "github", "google", or "twitter")base.authWithOAuthPopup("<provider>",authHandler);base.authWithOAuthRedirect("<provider>",authHandler);base.authWithOAuthToken("<provider>",token,authHandler);// Log a user outbase.unauth()// Get authentication informationvarauthData=base.getAuth();
// Listen to authenticationfunctionauthDataCallback(authData){if(authData){console.log("User "+authData.uid+" is logged in with "+authData.provider);}else{console.log("User is logged out");}}varref=newFirebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");ref.onAuth(authDataCallback);

re-base exposes createUser, removeUser, resetPassword and changePassword methods for user management.

// Createbase.createUser({email: 'bobtony@firebase.com',password: 'correcthorsebatterystaple'},userHandler);// Removebase.removeUser({email: 'bobtony@firebase.com',password: 'correcthorsebatterystaple'},errorHandler);// Reset Passwordbase.resetPassword({email: 'bobtony@firebase.com'},errorHandler);// Change Passwordbase.changePassword({email: 'bobtony@firebase.com',oldPassword: 'correcthorsebatterystaple',newPassword: 'chipsahoy'},errorHandler);

Contributing

  1. npm install
  2. Edit src/rebase.js
  3. Add/edit tests in tests/specs/re-base.spec.js
  4. npm run build
  5. npm run test

Credits

re-base is inspired by ReactFire from Firebase. Jacob Turner is also a core contributor and this wouldn't have been possible without his assistance.

License

MIT

About

🔥 A Relay inspired library for building React.js + Firebase applications. 🔥

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

re-base

Build StatusCoverage Status

welcome

Questions? Find me on twitter at @tylermcginnis33

What is re-base?

React.js makes managing state easy to reason about. Firebase makes persisting your data easy to implement. re-base, inspired by Relay, combines the benefits of React and Firebase by allowing each component to specify its own data dependency. Forget about your data persistence and focus on what really matters, your application's state.

Why re-base?

I spent a few weeks trying to figure out the cleanest way to implement Firebase into my React/Flux application. After struggling for a bit, I tweeted my frustrations. I was enlightened to the fact that Firebase and Flux really don't work well together. It makes sense why they don't work together, because they're both trying to accomplish roughly the same thing. So I did away with my reliance upon Flux and tried to think of a clean way to implement React with Firebase. I came across ReactFire built by Jacob Wenger at Firebase and loved his idea. Sync a Firebase endpoint with a property on your component's state. So whenever your data changes, your state will be updated. Simple as that. The problem with ReactFire is because it uses Mixins, it's not compatible with ES6 classes. After chatting with Jacob Turner, we wanted to create a way to allow the one way binding of ReactFire with ES6 classes along some more features like two way data binding and listening to Firebase endpoints without actually binding a state property to them. Thus, re-base was built.

Features

  • syncState: Two way data binding between any property on your component's state and any endpoint in Firebase. Use the same API you're used to to update your component's state (setState), and Firebase will also update.
  • bindToState: One way data binding. Whenever your Firebase endpoint changes, the property on your state will update as well.
  • listenTo: Whenever your Firebase endpoint changes, it will invoke a callback passing it the new data from Firebase.
  • fetch: Retrieve data from Firebase without setting up any binding or listeners.
  • post: Add new data to Firebase.
  • push: Push new child data to Firebase.
  • removeBinding: Remove all of the Firebase listeners when your component unmounts.
  • reset: Removes all of the Firebase listeners and resets the singleton (for testing purposes).

Installing

$ npm install re-base

API

For more in depth examples of the API, see the examples folder.

createClass(firebaseUrl)

Purpose

Accepts a firebase URL as its only parameter and returns a singleton with the re-base API.

Arguments
  1. firebaseUrl:
    • type: string
    • The absolute, HTTPS URL of your Firebase project
Return Value

An object with syncState, bindToState, listenTo, fetch, post, push, removeBinding, and reset methods.

Example
varRebase=require('re-base');varbase=Rebase.createClass('https://myapp.firebaseio.com');

syncState(endpoint, options)

Purpose

Allows you to set up two way data binding between your component's state and your Firebase. Whenever your Firebase changes, your component's state will change. Whenever your component's state changes, Firebase will change.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint to which you'd like to bind your component's state
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • state: (string - required) The state property you want to sync with Firebase
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.
    • then: (function - optional) The callback function that will be invoked when the initial listener is established with Firebase. Typically used (with syncState) to change this.state.loading to false.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.syncState(`shoppingList`,{context: this,state: 'items',asArray: true});}addItem(newItem){this.setState({items: this.state.items.concat([newItem])//updates Firebase and the local state});}

bindToState(endpoint, options)

Purpose

One way data binding from Firebase to your component's state. Allows you to bind a component's state property to a Firebase endpoint so whenever that Firebase endpoint changes, your component's state will be updated with that change.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like your component's state property to listen for changes
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • state: (string - required) The state property you want to sync with Firebase
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.bindToState('tasks',{context: this,state: 'tasks',asArray: true});}

listenTo(endpoint, options)

Purpose

Allows you to listen to Firebase endpoints without binding those changes to a state property. Instead, a callback will be invoked with the newly updated data.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint which contains the data with which you'd like to invoke your callback function
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • then: (function - required) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.listenTo('votes',{context: this,asArray: true,then(votesData){vartotal=0;votesData.forEach((vote,index)=>{total+=vote});this.setState({total});}})}

fetch(endpoint, options)

Purpose

Allows you to retrieve the data from a Firebase endpoint just once without subscribing or listening for data changes.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint which contains the data you're wanting to fetch
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • then: (function - required) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

No return value

Example

getSales(){base.fetch('sales',{context: this,asArray: true,then(data){console.log(data);}});}

post(endpoint, options)

Purpose

Allows you to update a Firebase endpoint with new data. Replace all the data at this endpoint with the new data

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like to update with the new data
  2. options - type: object - properties:
    • data: (any - required) The data you're wanting to persist to Firebase
    • then: (function - optional) A callback that will get invoked once the new data has been saved to Firebase

Return Value

No return value

Example

addUser(){base.post(`users/${userId}`,{data: {name: 'Tyler McGinnis',age: 25},then(){Router.transitionTo('dashboard');}});}

push(endpoint, options)

Purpose

Allows you to add data to a Firebase endpoint. Adds data to a child of the endpoint with a new Firebase push key

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like to push the new data to
  2. options - type: object - properties:
    • data: (any - required) The data you're wanting to persist to Firebase
    • then: (function - optional) A callback that will get invoked once the new data has been saved to Firebase

Return Value

A Firebase reference for the generated location

Example

addBear(){base.push('bears',{data: {name: 'George',type: 'Grizzly'},then(){Router.transitionTo('dashboard');}});}

removeBinding(ref)

Purpose

Remove the listeners to Firebase when your component unmounts.

Arguments

  1. ref - type: Object - The return value of syncState, bindToState, or listenTo

Return Value

No return value

Example

componentDidMount(){this.ref=base.syncState('users',{context: this,state: 'users'});}componentWillUnmount(){base.removeBinding(this.ref);}

reset()

Purpose

Removes every Firebase listener and resets all private variables. Used for testing purposes.

Arguments

No Arguments

Return Value

No return value


Use the query option to utilize the Firebase Query API. For a list of available queries and how they work, see the Firebase docs.

Queries are accepted in the options object of each read method (syncState, bindToState, listenTo, and fetch). The object should have one or more keys of the type of query you wish to run, with the value being the value for the query. For example:

base.syncState('users',{context: this,state: 'users',asArray: true,queries: {orderByChild: 'iq',limitToLast: 3}})

The binding above will sort the users endpoint by iq, retrieve the last three (or, three with highest iq), and bind it to the component's users state. NOTE: This query is happening within Firebase. The only data that will be retrieved are the three users with the highest iq.

re-base exposes Firebase's web clientauthWithPassword, authWithCustomToken, authWithOAuthPopup, authWithOAuthRedirect, authWithOAuthToken methods to allow user authentication. getAuth is also exposed to access the current authentication state.

// Simple email authenticationbase.authWithPassword({email : 'bobtony@firebase.com',password : 'correcthorsebatterystaple'},authHandler);// Authentication via a custom authentication tokenbase.authWithCustomToken(token,authHandler);// Authentication via OAuth providers ("facebook", "github", "google", or "twitter")base.authWithOAuthPopup("<provider>",authHandler);base.authWithOAuthRedirect("<provider>",authHandler);base.authWithOAuthToken("<provider>",token,authHandler);// Log a user outbase.unauth()// Get authentication informationvarauthData=base.getAuth();
// Listen to authenticationfunctionauthDataCallback(authData){if(authData){console.log("User "+authData.uid+" is logged in with "+authData.provider);}else{console.log("User is logged out");}}varref=newFirebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");ref.onAuth(authDataCallback);

re-base exposes createUser, removeUser, resetPassword and changePassword methods for user management.

// Createbase.createUser({email: 'bobtony@firebase.com',password: 'correcthorsebatterystaple'},userHandler);// Removebase.removeUser({email: 'bobtony@firebase.com',password: 'correcthorsebatterystaple'},errorHandler);// Reset Passwordbase.resetPassword({email: 'bobtony@firebase.com'},errorHandler);// Change Passwordbase.changePassword({email: 'bobtony@firebase.com',oldPassword: 'correcthorsebatterystaple',newPassword: 'chipsahoy'},errorHandler);

Contributing

  1. npm install
  2. Edit src/rebase.js
  3. Add/edit tests in tests/specs/re-base.spec.js
  4. npm run build
  5. npm run test

Credits

re-base is inspired by ReactFire from Firebase. Jacob Turner is also a core contributor and this wouldn't have been possible without his assistance.

License

MIT

About

🔥 A Relay inspired library for building React.js + Firebase applications. 🔥

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

re-base

Build StatusCoverage Status

welcome

Questions? Find me on twitter at @tylermcginnis33

What is re-base?

React.js makes managing state easy to reason about. Firebase makes persisting your data easy to implement. re-base, inspired by Relay, combines the benefits of React and Firebase by allowing each component to specify its own data dependency. Forget about your data persistence and focus on what really matters, your application's state.

Why re-base?

I spent a few weeks trying to figure out the cleanest way to implement Firebase into my React/Flux application. After struggling for a bit, I tweeted my frustrations. I was enlightened to the fact that Firebase and Flux really don't work well together. It makes sense why they don't work together, because they're both trying to accomplish roughly the same thing. So I did away with my reliance upon Flux and tried to think of a clean way to implement React with Firebase. I came across ReactFire built by Jacob Wenger at Firebase and loved his idea. Sync a Firebase endpoint with a property on your component's state. So whenever your data changes, your state will be updated. Simple as that. The problem with ReactFire is because it uses Mixins, it's not compatible with ES6 classes. After chatting with Jacob Turner, we wanted to create a way to allow the one way binding of ReactFire with ES6 classes along some more features like two way data binding and listening to Firebase endpoints without actually binding a state property to them. Thus, re-base was built.

Features

  • syncState: Two way data binding between any property on your component's state and any endpoint in Firebase. Use the same API you're used to to update your component's state (setState), and Firebase will also update.
  • bindToState: One way data binding. Whenever your Firebase endpoint changes, the property on your state will update as well.
  • listenTo: Whenever your Firebase endpoint changes, it will invoke a callback passing it the new data from Firebase.
  • fetch: Retrieve data from Firebase without setting up any binding or listeners.
  • post: Add new data to Firebase.
  • push: Push new child data to Firebase.
  • removeBinding: Remove all of the Firebase listeners when your component unmounts.
  • reset: Removes all of the Firebase listeners and resets the singleton (for testing purposes).

Installing

$ npm install re-base

API

For more in depth examples of the API, see the examples folder.

createClass(firebaseUrl)

Purpose

Accepts a firebase URL as its only parameter and returns a singleton with the re-base API.

Arguments
  1. firebaseUrl:
    • type: string
    • The absolute, HTTPS URL of your Firebase project
Return Value

An object with syncState, bindToState, listenTo, fetch, post, push, removeBinding, and reset methods.

Example
varRebase=require('re-base');varbase=Rebase.createClass('https://myapp.firebaseio.com');

syncState(endpoint, options)

Purpose

Allows you to set up two way data binding between your component's state and your Firebase. Whenever your Firebase changes, your component's state will change. Whenever your component's state changes, Firebase will change.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint to which you'd like to bind your component's state
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • state: (string - required) The state property you want to sync with Firebase
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.
    • then: (function - optional) The callback function that will be invoked when the initial listener is established with Firebase. Typically used (with syncState) to change this.state.loading to false.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.syncState(`shoppingList`,{context: this,state: 'items',asArray: true});}addItem(newItem){this.setState({items: this.state.items.concat([newItem])//updates Firebase and the local state});}

bindToState(endpoint, options)

Purpose

One way data binding from Firebase to your component's state. Allows you to bind a component's state property to a Firebase endpoint so whenever that Firebase endpoint changes, your component's state will be updated with that change.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like your component's state property to listen for changes
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • state: (string - required) The state property you want to sync with Firebase
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.bindToState('tasks',{context: this,state: 'tasks',asArray: true});}

listenTo(endpoint, options)

Purpose

Allows you to listen to Firebase endpoints without binding those changes to a state property. Instead, a callback will be invoked with the newly updated data.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint which contains the data with which you'd like to invoke your callback function
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • then: (function - required) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.listenTo('votes',{context: this,asArray: true,then(votesData){vartotal=0;votesData.forEach((vote,index)=>{total+=vote});this.setState({total});}})}

fetch(endpoint, options)

Purpose

Allows you to retrieve the data from a Firebase endpoint just once without subscribing or listening for data changes.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint which contains the data you're wanting to fetch
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • then: (function - required) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

No return value

Example

getSales(){base.fetch('sales',{context: this,asArray: true,then(data){console.log(data);}});}

post(endpoint, options)

Purpose

Allows you to update a Firebase endpoint with new data. Replace all the data at this endpoint with the new data

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like to update with the new data
  2. options - type: object - properties:
    • data: (any - required) The data you're wanting to persist to Firebase
    • then: (function - optional) A callback that will get invoked once the new data has been saved to Firebase

Return Value

No return value

Example

addUser(){base.post(`users/${userId}`,{data: {name: 'Tyler McGinnis',age: 25},then(){Router.transitionTo('dashboard');}});}

push(endpoint, options)

Purpose

Allows you to add data to a Firebase endpoint. Adds data to a child of the endpoint with a new Firebase push key

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like to push the new data to
  2. options - type: object - properties:
    • data: (any - required) The data you're wanting to persist to Firebase
    • then: (function - optional) A callback that will get invoked once the new data has been saved to Firebase

Return Value

A Firebase reference for the generated location

Example

addBear(){base.push('bears',{data: {name: 'George',type: 'Grizzly'},then(){Router.transitionTo('dashboard');}});}

removeBinding(ref)

Purpose

Remove the listeners to Firebase when your component unmounts.

Arguments

  1. ref - type: Object - The return value of syncState, bindToState, or listenTo

Return Value

No return value

Example

componentDidMount(){this.ref=base.syncState('users',{context: this,state: 'users'});}componentWillUnmount(){base.removeBinding(this.ref);}

reset()

Purpose

Removes every Firebase listener and resets all private variables. Used for testing purposes.

Arguments

No Arguments

Return Value

No return value


Use the query option to utilize the Firebase Query API. For a list of available queries and how they work, see the Firebase docs.

Queries are accepted in the options object of each read method (syncState, bindToState, listenTo, and fetch). The object should have one or more keys of the type of query you wish to run, with the value being the value for the query. For example:

base.syncState('users',{context: this,state: 'users',asArray: true,queries: {orderByChild: 'iq',limitToLast: 3}})

The binding above will sort the users endpoint by iq, retrieve the last three (or, three with highest iq), and bind it to the component's users state. NOTE: This query is happening within Firebase. The only data that will be retrieved are the three users with the highest iq.

re-base exposes Firebase's web clientauthWithPassword, authWithCustomToken, authWithOAuthPopup, authWithOAuthRedirect, authWithOAuthToken methods to allow user authentication. getAuth is also exposed to access the current authentication state.

// Simple email authenticationbase.authWithPassword({email : 'bobtony@firebase.com',password : 'correcthorsebatterystaple'},authHandler);// Authentication via a custom authentication tokenbase.authWithCustomToken(token,authHandler);// Authentication via OAuth providers ("facebook", "github", "google", or "twitter")base.authWithOAuthPopup("<provider>",authHandler);base.authWithOAuthRedirect("<provider>",authHandler);base.authWithOAuthToken("<provider>",token,authHandler);// Log a user outbase.unauth()// Get authentication informationvarauthData=base.getAuth();
// Listen to authenticationfunctionauthDataCallback(authData){if(authData){console.log("User "+authData.uid+" is logged in with "+authData.provider);}else{console.log("User is logged out");}}varref=newFirebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");ref.onAuth(authDataCallback);

re-base exposes createUser, removeUser, resetPassword and changePassword methods for user management.

// Createbase.createUser({email: 'bobtony@firebase.com',password: 'correcthorsebatterystaple'},userHandler);// Removebase.removeUser({email: 'bobtony@firebase.com',password: 'correcthorsebatterystaple'},errorHandler);// Reset Passwordbase.resetPassword({email: 'bobtony@firebase.com'},errorHandler);// Change Passwordbase.changePassword({email: 'bobtony@firebase.com',oldPassword: 'correcthorsebatterystaple',newPassword: 'chipsahoy'},errorHandler);

Contributing

  1. npm install
  2. Edit src/rebase.js
  3. Add/edit tests in tests/specs/re-base.spec.js
  4. npm run build
  5. npm run test

Credits

re-base is inspired by ReactFire from Firebase. Jacob Turner is also a core contributor and this wouldn't have been possible without his assistance.

License

MIT

About

🔥 A Relay inspired library for building React.js + Firebase applications. 🔥

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

re-base

Build StatusCoverage Status

welcome

Questions? Find me on twitter at @tylermcginnis33

What is re-base?

React.js makes managing state easy to reason about. Firebase makes persisting your data easy to implement. re-base, inspired by Relay, combines the benefits of React and Firebase by allowing each component to specify its own data dependency. Forget about your data persistence and focus on what really matters, your application's state.

Why re-base?

I spent a few weeks trying to figure out the cleanest way to implement Firebase into my React/Flux application. After struggling for a bit, I tweeted my frustrations. I was enlightened to the fact that Firebase and Flux really don't work well together. It makes sense why they don't work together, because they're both trying to accomplish roughly the same thing. So I did away with my reliance upon Flux and tried to think of a clean way to implement React with Firebase. I came across ReactFire built by Jacob Wenger at Firebase and loved his idea. Sync a Firebase endpoint with a property on your component's state. So whenever your data changes, your state will be updated. Simple as that. The problem with ReactFire is because it uses Mixins, it's not compatible with ES6 classes. After chatting with Jacob Turner, we wanted to create a way to allow the one way binding of ReactFire with ES6 classes along some more features like two way data binding and listening to Firebase endpoints without actually binding a state property to them. Thus, re-base was built.

Features

  • syncState: Two way data binding between any property on your component's state and any endpoint in Firebase. Use the same API you're used to to update your component's state (setState), and Firebase will also update.
  • bindToState: One way data binding. Whenever your Firebase endpoint changes, the property on your state will update as well.
  • listenTo: Whenever your Firebase endpoint changes, it will invoke a callback passing it the new data from Firebase.
  • fetch: Retrieve data from Firebase without setting up any binding or listeners.
  • post: Add new data to Firebase.
  • push: Push new child data to Firebase.
  • removeBinding: Remove all of the Firebase listeners when your component unmounts.
  • reset: Removes all of the Firebase listeners and resets the singleton (for testing purposes).

Installing

$ npm install re-base

API

For more in depth examples of the API, see the examples folder.

createClass(firebaseUrl)

Purpose

Accepts a firebase URL as its only parameter and returns a singleton with the re-base API.

Arguments
  1. firebaseUrl:
    • type: string
    • The absolute, HTTPS URL of your Firebase project
Return Value

An object with syncState, bindToState, listenTo, fetch, post, push, removeBinding, and reset methods.

Example
varRebase=require('re-base');varbase=Rebase.createClass('https://myapp.firebaseio.com');

syncState(endpoint, options)

Purpose

Allows you to set up two way data binding between your component's state and your Firebase. Whenever your Firebase changes, your component's state will change. Whenever your component's state changes, Firebase will change.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint to which you'd like to bind your component's state
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • state: (string - required) The state property you want to sync with Firebase
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.
    • then: (function - optional) The callback function that will be invoked when the initial listener is established with Firebase. Typically used (with syncState) to change this.state.loading to false.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.syncState(`shoppingList`,{context: this,state: 'items',asArray: true});}addItem(newItem){this.setState({items: this.state.items.concat([newItem])//updates Firebase and the local state});}

bindToState(endpoint, options)

Purpose

One way data binding from Firebase to your component's state. Allows you to bind a component's state property to a Firebase endpoint so whenever that Firebase endpoint changes, your component's state will be updated with that change.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like your component's state property to listen for changes
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • state: (string - required) The state property you want to sync with Firebase
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.bindToState('tasks',{context: this,state: 'tasks',asArray: true});}

listenTo(endpoint, options)

Purpose

Allows you to listen to Firebase endpoints without binding those changes to a state property. Instead, a callback will be invoked with the newly updated data.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint which contains the data with which you'd like to invoke your callback function
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • then: (function - required) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.listenTo('votes',{context: this,asArray: true,then(votesData){vartotal=0;votesData.forEach((vote,index)=>{total+=vote});this.setState({total});}})}

fetch(endpoint, options)

Purpose

Allows you to retrieve the data from a Firebase endpoint just once without subscribing or listening for data changes.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint which contains the data you're wanting to fetch
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • then: (function - required) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

No return value

Example

getSales(){base.fetch('sales',{context: this,asArray: true,then(data){console.log(data);}});}

post(endpoint, options)

Purpose

Allows you to update a Firebase endpoint with new data. Replace all the data at this endpoint with the new data

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like to update with the new data
  2. options - type: object - properties:
    • data: (any - required) The data you're wanting to persist to Firebase
    • then: (function - optional) A callback that will get invoked once the new data has been saved to Firebase

Return Value

No return value

Example

addUser(){base.post(`users/${userId}`,{data: {name: 'Tyler McGinnis',age: 25},then(){Router.transitionTo('dashboard');}});}

push(endpoint, options)

Purpose

Allows you to add data to a Firebase endpoint. Adds data to a child of the endpoint with a new Firebase push key

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like to push the new data to
  2. options - type: object - properties:
    • data: (any - required) The data you're wanting to persist to Firebase
    • then: (function - optional) A callback that will get invoked once the new data has been saved to Firebase

Return Value

A Firebase reference for the generated location

Example

addBear(){base.push('bears',{data: {name: 'George',type: 'Grizzly'},then(){Router.transitionTo('dashboard');}});}

removeBinding(ref)

Purpose

Remove the listeners to Firebase when your component unmounts.

Arguments

  1. ref - type: Object - The return value of syncState, bindToState, or listenTo

Return Value

No return value

Example

componentDidMount(){this.ref=base.syncState('users',{context: this,state: 'users'});}componentWillUnmount(){base.removeBinding(this.ref);}

reset()

Purpose

Removes every Firebase listener and resets all private variables. Used for testing purposes.

Arguments

No Arguments

Return Value

No return value


Use the query option to utilize the Firebase Query API. For a list of available queries and how they work, see the Firebase docs.

Queries are accepted in the options object of each read method (syncState, bindToState, listenTo, and fetch). The object should have one or more keys of the type of query you wish to run, with the value being the value for the query. For example:

base.syncState('users',{context: this,state: 'users',asArray: true,queries: {orderByChild: 'iq',limitToLast: 3}})

The binding above will sort the users endpoint by iq, retrieve the last three (or, three with highest iq), and bind it to the component's users state. NOTE: This query is happening within Firebase. The only data that will be retrieved are the three users with the highest iq.

re-base exposes Firebase's web clientauthWithPassword, authWithCustomToken, authWithOAuthPopup, authWithOAuthRedirect, authWithOAuthToken methods to allow user authentication. getAuth is also exposed to access the current authentication state.

// Simple email authenticationbase.authWithPassword({email : 'bobtony@firebase.com',password : 'correcthorsebatterystaple'},authHandler);// Authentication via a custom authentication tokenbase.authWithCustomToken(token,authHandler);// Authentication via OAuth providers ("facebook", "github", "google", or "twitter")base.authWithOAuthPopup("<provider>",authHandler);base.authWithOAuthRedirect("<provider>",authHandler);base.authWithOAuthToken("<provider>",token,authHandler);// Log a user outbase.unauth()// Get authentication informationvarauthData=base.getAuth();
// Listen to authenticationfunctionauthDataCallback(authData){if(authData){console.log("User "+authData.uid+" is logged in with "+authData.provider);}else{console.log("User is logged out");}}varref=newFirebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");ref.onAuth(authDataCallback);

re-base exposes createUser, removeUser, resetPassword and changePassword methods for user management.

// Createbase.createUser({email: 'bobtony@firebase.com',password: 'correcthorsebatterystaple'},userHandler);// Removebase.removeUser({email: 'bobtony@firebase.com',password: 'correcthorsebatterystaple'},errorHandler);// Reset Passwordbase.resetPassword({email: 'bobtony@firebase.com'},errorHandler);// Change Passwordbase.changePassword({email: 'bobtony@firebase.com',oldPassword: 'correcthorsebatterystaple',newPassword: 'chipsahoy'},errorHandler);

Contributing

  1. npm install
  2. Edit src/rebase.js
  3. Add/edit tests in tests/specs/re-base.spec.js
  4. npm run build
  5. npm run test

Credits

re-base is inspired by ReactFire from Firebase. Jacob Turner is also a core contributor and this wouldn't have been possible without his assistance.

License

MIT

About

🔥 A Relay inspired library for building React.js + Firebase applications. 🔥

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

re-base

Build StatusCoverage Status

welcome

Questions? Find me on twitter at @tylermcginnis33

What is re-base?

React.js makes managing state easy to reason about. Firebase makes persisting your data easy to implement. re-base, inspired by Relay, combines the benefits of React and Firebase by allowing each component to specify its own data dependency. Forget about your data persistence and focus on what really matters, your application's state.

Why re-base?

I spent a few weeks trying to figure out the cleanest way to implement Firebase into my React/Flux application. After struggling for a bit, I tweeted my frustrations. I was enlightened to the fact that Firebase and Flux really don't work well together. It makes sense why they don't work together, because they're both trying to accomplish roughly the same thing. So I did away with my reliance upon Flux and tried to think of a clean way to implement React with Firebase. I came across ReactFire built by Jacob Wenger at Firebase and loved his idea. Sync a Firebase endpoint with a property on your component's state. So whenever your data changes, your state will be updated. Simple as that. The problem with ReactFire is because it uses Mixins, it's not compatible with ES6 classes. After chatting with Jacob Turner, we wanted to create a way to allow the one way binding of ReactFire with ES6 classes along some more features like two way data binding and listening to Firebase endpoints without actually binding a state property to them. Thus, re-base was built.

Features

  • syncState: Two way data binding between any property on your component's state and any endpoint in Firebase. Use the same API you're used to to update your component's state (setState), and Firebase will also update.
  • bindToState: One way data binding. Whenever your Firebase endpoint changes, the property on your state will update as well.
  • listenTo: Whenever your Firebase endpoint changes, it will invoke a callback passing it the new data from Firebase.
  • fetch: Retrieve data from Firebase without setting up any binding or listeners.
  • post: Add new data to Firebase.
  • push: Push new child data to Firebase.
  • removeBinding: Remove all of the Firebase listeners when your component unmounts.
  • reset: Removes all of the Firebase listeners and resets the singleton (for testing purposes).

Installing

$ npm install re-base

API

For more in depth examples of the API, see the examples folder.

createClass(firebaseUrl)

Purpose

Accepts a firebase URL as its only parameter and returns a singleton with the re-base API.

Arguments
  1. firebaseUrl:
    • type: string
    • The absolute, HTTPS URL of your Firebase project
Return Value

An object with syncState, bindToState, listenTo, fetch, post, push, removeBinding, and reset methods.

Example
varRebase=require('re-base');varbase=Rebase.createClass('https://myapp.firebaseio.com');

syncState(endpoint, options)

Purpose

Allows you to set up two way data binding between your component's state and your Firebase. Whenever your Firebase changes, your component's state will change. Whenever your component's state changes, Firebase will change.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint to which you'd like to bind your component's state
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • state: (string - required) The state property you want to sync with Firebase
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.
    • then: (function - optional) The callback function that will be invoked when the initial listener is established with Firebase. Typically used (with syncState) to change this.state.loading to false.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.syncState(`shoppingList`,{context: this,state: 'items',asArray: true});}addItem(newItem){this.setState({items: this.state.items.concat([newItem])//updates Firebase and the local state});}

bindToState(endpoint, options)

Purpose

One way data binding from Firebase to your component's state. Allows you to bind a component's state property to a Firebase endpoint so whenever that Firebase endpoint changes, your component's state will be updated with that change.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like your component's state property to listen for changes
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • state: (string - required) The state property you want to sync with Firebase
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.bindToState('tasks',{context: this,state: 'tasks',asArray: true});}

listenTo(endpoint, options)

Purpose

Allows you to listen to Firebase endpoints without binding those changes to a state property. Instead, a callback will be invoked with the newly updated data.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint which contains the data with which you'd like to invoke your callback function
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • then: (function - required) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.listenTo('votes',{context: this,asArray: true,then(votesData){vartotal=0;votesData.forEach((vote,index)=>{total+=vote});this.setState({total});}})}

fetch(endpoint, options)

Purpose

Allows you to retrieve the data from a Firebase endpoint just once without subscribing or listening for data changes.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint which contains the data you're wanting to fetch
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • then: (function - required) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

No return value

Example

getSales(){base.fetch('sales',{context: this,asArray: true,then(data){console.log(data);}});}

post(endpoint, options)

Purpose

Allows you to update a Firebase endpoint with new data. Replace all the data at this endpoint with the new data

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like to update with the new data
  2. options - type: object - properties:
    • data: (any - required) The data you're wanting to persist to Firebase
    • then: (function - optional) A callback that will get invoked once the new data has been saved to Firebase

Return Value

No return value

Example

addUser(){base.post(`users/${userId}`,{data: {name: 'Tyler McGinnis',age: 25},then(){Router.transitionTo('dashboard');}});}

push(endpoint, options)

Purpose

Allows you to add data to a Firebase endpoint. Adds data to a child of the endpoint with a new Firebase push key

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like to push the new data to
  2. options - type: object - properties:
    • data: (any - required) The data you're wanting to persist to Firebase
    • then: (function - optional) A callback that will get invoked once the new data has been saved to Firebase

Return Value

A Firebase reference for the generated location

Example

addBear(){base.push('bears',{data: {name: 'George',type: 'Grizzly'},then(){Router.transitionTo('dashboard');}});}

removeBinding(ref)

Purpose

Remove the listeners to Firebase when your component unmounts.

Arguments

  1. ref - type: Object - The return value of syncState, bindToState, or listenTo

Return Value

No return value

Example

componentDidMount(){this.ref=base.syncState('users',{context: this,state: 'users'});}componentWillUnmount(){base.removeBinding(this.ref);}

reset()

Purpose

Removes every Firebase listener and resets all private variables. Used for testing purposes.

Arguments

No Arguments

Return Value

No return value


Use the query option to utilize the Firebase Query API. For a list of available queries and how they work, see the Firebase docs.

Queries are accepted in the options object of each read method (syncState, bindToState, listenTo, and fetch). The object should have one or more keys of the type of query you wish to run, with the value being the value for the query. For example:

base.syncState('users',{context: this,state: 'users',asArray: true,queries: {orderByChild: 'iq',limitToLast: 3}})

The binding above will sort the users endpoint by iq, retrieve the last three (or, three with highest iq), and bind it to the component's users state. NOTE: This query is happening within Firebase. The only data that will be retrieved are the three users with the highest iq.

re-base exposes Firebase's web clientauthWithPassword, authWithCustomToken, authWithOAuthPopup, authWithOAuthRedirect, authWithOAuthToken methods to allow user authentication. getAuth is also exposed to access the current authentication state.

// Simple email authenticationbase.authWithPassword({email : 'bobtony@firebase.com',password : 'correcthorsebatterystaple'},authHandler);// Authentication via a custom authentication tokenbase.authWithCustomToken(token,authHandler);// Authentication via OAuth providers ("facebook", "github", "google", or "twitter")base.authWithOAuthPopup("<provider>",authHandler);base.authWithOAuthRedirect("<provider>",authHandler);base.authWithOAuthToken("<provider>",token,authHandler);// Log a user outbase.unauth()// Get authentication informationvarauthData=base.getAuth();
// Listen to authenticationfunctionauthDataCallback(authData){if(authData){console.log("User "+authData.uid+" is logged in with "+authData.provider);}else{console.log("User is logged out");}}varref=newFirebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");ref.onAuth(authDataCallback);

re-base exposes createUser, removeUser, resetPassword and changePassword methods for user management.

// Createbase.createUser({email: 'bobtony@firebase.com',password: 'correcthorsebatterystaple'},userHandler);// Removebase.removeUser({email: 'bobtony@firebase.com',password: 'correcthorsebatterystaple'},errorHandler);// Reset Passwordbase.resetPassword({email: 'bobtony@firebase.com'},errorHandler);// Change Passwordbase.changePassword({email: 'bobtony@firebase.com',oldPassword: 'correcthorsebatterystaple',newPassword: 'chipsahoy'},errorHandler);

Contributing

  1. npm install
  2. Edit src/rebase.js
  3. Add/edit tests in tests/specs/re-base.spec.js
  4. npm run build
  5. npm run test

Credits

re-base is inspired by ReactFire from Firebase. Jacob Turner is also a core contributor and this wouldn't have been possible without his assistance.

License

MIT

About

🔥 A Relay inspired library for building React.js + Firebase applications. 🔥

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

re-base

Build StatusCoverage Status

welcome

Questions? Find me on twitter at @tylermcginnis33

What is re-base?

React.js makes managing state easy to reason about. Firebase makes persisting your data easy to implement. re-base, inspired by Relay, combines the benefits of React and Firebase by allowing each component to specify its own data dependency. Forget about your data persistence and focus on what really matters, your application's state.

Why re-base?

I spent a few weeks trying to figure out the cleanest way to implement Firebase into my React/Flux application. After struggling for a bit, I tweeted my frustrations. I was enlightened to the fact that Firebase and Flux really don't work well together. It makes sense why they don't work together, because they're both trying to accomplish roughly the same thing. So I did away with my reliance upon Flux and tried to think of a clean way to implement React with Firebase. I came across ReactFire built by Jacob Wenger at Firebase and loved his idea. Sync a Firebase endpoint with a property on your component's state. So whenever your data changes, your state will be updated. Simple as that. The problem with ReactFire is because it uses Mixins, it's not compatible with ES6 classes. After chatting with Jacob Turner, we wanted to create a way to allow the one way binding of ReactFire with ES6 classes along some more features like two way data binding and listening to Firebase endpoints without actually binding a state property to them. Thus, re-base was built.

Features

  • syncState: Two way data binding between any property on your component's state and any endpoint in Firebase. Use the same API you're used to to update your component's state (setState), and Firebase will also update.
  • bindToState: One way data binding. Whenever your Firebase endpoint changes, the property on your state will update as well.
  • listenTo: Whenever your Firebase endpoint changes, it will invoke a callback passing it the new data from Firebase.
  • fetch: Retrieve data from Firebase without setting up any binding or listeners.
  • post: Add new data to Firebase.
  • push: Push new child data to Firebase.
  • removeBinding: Remove all of the Firebase listeners when your component unmounts.
  • reset: Removes all of the Firebase listeners and resets the singleton (for testing purposes).

Installing

$ npm install re-base

API

For more in depth examples of the API, see the examples folder.

createClass(firebaseUrl)

Purpose

Accepts a firebase URL as its only parameter and returns a singleton with the re-base API.

Arguments
  1. firebaseUrl:
    • type: string
    • The absolute, HTTPS URL of your Firebase project
Return Value

An object with syncState, bindToState, listenTo, fetch, post, push, removeBinding, and reset methods.

Example
varRebase=require('re-base');varbase=Rebase.createClass('https://myapp.firebaseio.com');

syncState(endpoint, options)

Purpose

Allows you to set up two way data binding between your component's state and your Firebase. Whenever your Firebase changes, your component's state will change. Whenever your component's state changes, Firebase will change.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint to which you'd like to bind your component's state
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • state: (string - required) The state property you want to sync with Firebase
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.
    • then: (function - optional) The callback function that will be invoked when the initial listener is established with Firebase. Typically used (with syncState) to change this.state.loading to false.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.syncState(`shoppingList`,{context: this,state: 'items',asArray: true});}addItem(newItem){this.setState({items: this.state.items.concat([newItem])//updates Firebase and the local state});}

bindToState(endpoint, options)

Purpose

One way data binding from Firebase to your component's state. Allows you to bind a component's state property to a Firebase endpoint so whenever that Firebase endpoint changes, your component's state will be updated with that change.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like your component's state property to listen for changes
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • state: (string - required) The state property you want to sync with Firebase
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.bindToState('tasks',{context: this,state: 'tasks',asArray: true});}

listenTo(endpoint, options)

Purpose

Allows you to listen to Firebase endpoints without binding those changes to a state property. Instead, a callback will be invoked with the newly updated data.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint which contains the data with which you'd like to invoke your callback function
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • then: (function - required) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.listenTo('votes',{context: this,asArray: true,then(votesData){vartotal=0;votesData.forEach((vote,index)=>{total+=vote});this.setState({total});}})}

fetch(endpoint, options)

Purpose

Allows you to retrieve the data from a Firebase endpoint just once without subscribing or listening for data changes.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint which contains the data you're wanting to fetch
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • then: (function - required) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

No return value

Example

getSales(){base.fetch('sales',{context: this,asArray: true,then(data){console.log(data);}});}

post(endpoint, options)

Purpose

Allows you to update a Firebase endpoint with new data. Replace all the data at this endpoint with the new data

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like to update with the new data
  2. options - type: object - properties:
    • data: (any - required) The data you're wanting to persist to Firebase
    • then: (function - optional) A callback that will get invoked once the new data has been saved to Firebase

Return Value

No return value

Example

addUser(){base.post(`users/${userId}`,{data: {name: 'Tyler McGinnis',age: 25},then(){Router.transitionTo('dashboard');}});}

push(endpoint, options)

Purpose

Allows you to add data to a Firebase endpoint. Adds data to a child of the endpoint with a new Firebase push key

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like to push the new data to
  2. options - type: object - properties:
    • data: (any - required) The data you're wanting to persist to Firebase
    • then: (function - optional) A callback that will get invoked once the new data has been saved to Firebase

Return Value

A Firebase reference for the generated location

Example

addBear(){base.push('bears',{data: {name: 'George',type: 'Grizzly'},then(){Router.transitionTo('dashboard');}});}

removeBinding(ref)

Purpose

Remove the listeners to Firebase when your component unmounts.

Arguments

  1. ref - type: Object - The return value of syncState, bindToState, or listenTo

Return Value

No return value

Example

componentDidMount(){this.ref=base.syncState('users',{context: this,state: 'users'});}componentWillUnmount(){base.removeBinding(this.ref);}

reset()

Purpose

Removes every Firebase listener and resets all private variables. Used for testing purposes.

Arguments

No Arguments

Return Value

No return value


Use the query option to utilize the Firebase Query API. For a list of available queries and how they work, see the Firebase docs.

Queries are accepted in the options object of each read method (syncState, bindToState, listenTo, and fetch). The object should have one or more keys of the type of query you wish to run, with the value being the value for the query. For example:

base.syncState('users',{context: this,state: 'users',asArray: true,queries: {orderByChild: 'iq',limitToLast: 3}})

The binding above will sort the users endpoint by iq, retrieve the last three (or, three with highest iq), and bind it to the component's users state. NOTE: This query is happening within Firebase. The only data that will be retrieved are the three users with the highest iq.

re-base exposes Firebase's web clientauthWithPassword, authWithCustomToken, authWithOAuthPopup, authWithOAuthRedirect, authWithOAuthToken methods to allow user authentication. getAuth is also exposed to access the current authentication state.

// Simple email authenticationbase.authWithPassword({email : 'bobtony@firebase.com',password : 'correcthorsebatterystaple'},authHandler);// Authentication via a custom authentication tokenbase.authWithCustomToken(token,authHandler);// Authentication via OAuth providers ("facebook", "github", "google", or "twitter")base.authWithOAuthPopup("<provider>",authHandler);base.authWithOAuthRedirect("<provider>",authHandler);base.authWithOAuthToken("<provider>",token,authHandler);// Log a user outbase.unauth()// Get authentication informationvarauthData=base.getAuth();
// Listen to authenticationfunctionauthDataCallback(authData){if(authData){console.log("User "+authData.uid+" is logged in with "+authData.provider);}else{console.log("User is logged out");}}varref=newFirebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");ref.onAuth(authDataCallback);

re-base exposes createUser, removeUser, resetPassword and changePassword methods for user management.

// Createbase.createUser({email: 'bobtony@firebase.com',password: 'correcthorsebatterystaple'},userHandler);// Removebase.removeUser({email: 'bobtony@firebase.com',password: 'correcthorsebatterystaple'},errorHandler);// Reset Passwordbase.resetPassword({email: 'bobtony@firebase.com'},errorHandler);// Change Passwordbase.changePassword({email: 'bobtony@firebase.com',oldPassword: 'correcthorsebatterystaple',newPassword: 'chipsahoy'},errorHandler);

Contributing

  1. npm install
  2. Edit src/rebase.js
  3. Add/edit tests in tests/specs/re-base.spec.js
  4. npm run build
  5. npm run test

Credits

re-base is inspired by ReactFire from Firebase. Jacob Turner is also a core contributor and this wouldn't have been possible without his assistance.

License

MIT

About

🔥 A Relay inspired library for building React.js + Firebase applications. 🔥

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

re-base

Build StatusCoverage Status

welcome

Questions? Find me on twitter at @tylermcginnis33

What is re-base?

React.js makes managing state easy to reason about. Firebase makes persisting your data easy to implement. re-base, inspired by Relay, combines the benefits of React and Firebase by allowing each component to specify its own data dependency. Forget about your data persistence and focus on what really matters, your application's state.

Why re-base?

I spent a few weeks trying to figure out the cleanest way to implement Firebase into my React/Flux application. After struggling for a bit, I tweeted my frustrations. I was enlightened to the fact that Firebase and Flux really don't work well together. It makes sense why they don't work together, because they're both trying to accomplish roughly the same thing. So I did away with my reliance upon Flux and tried to think of a clean way to implement React with Firebase. I came across ReactFire built by Jacob Wenger at Firebase and loved his idea. Sync a Firebase endpoint with a property on your component's state. So whenever your data changes, your state will be updated. Simple as that. The problem with ReactFire is because it uses Mixins, it's not compatible with ES6 classes. After chatting with Jacob Turner, we wanted to create a way to allow the one way binding of ReactFire with ES6 classes along some more features like two way data binding and listening to Firebase endpoints without actually binding a state property to them. Thus, re-base was built.

Features

  • syncState: Two way data binding between any property on your component's state and any endpoint in Firebase. Use the same API you're used to to update your component's state (setState), and Firebase will also update.
  • bindToState: One way data binding. Whenever your Firebase endpoint changes, the property on your state will update as well.
  • listenTo: Whenever your Firebase endpoint changes, it will invoke a callback passing it the new data from Firebase.
  • fetch: Retrieve data from Firebase without setting up any binding or listeners.
  • post: Add new data to Firebase.
  • push: Push new child data to Firebase.
  • removeBinding: Remove all of the Firebase listeners when your component unmounts.
  • reset: Removes all of the Firebase listeners and resets the singleton (for testing purposes).

Installing

$ npm install re-base

API

For more in depth examples of the API, see the examples folder.

createClass(firebaseUrl)

Purpose

Accepts a firebase URL as its only parameter and returns a singleton with the re-base API.

Arguments
  1. firebaseUrl:
    • type: string
    • The absolute, HTTPS URL of your Firebase project
Return Value

An object with syncState, bindToState, listenTo, fetch, post, push, removeBinding, and reset methods.

Example
varRebase=require('re-base');varbase=Rebase.createClass('https://myapp.firebaseio.com');

syncState(endpoint, options)

Purpose

Allows you to set up two way data binding between your component's state and your Firebase. Whenever your Firebase changes, your component's state will change. Whenever your component's state changes, Firebase will change.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint to which you'd like to bind your component's state
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • state: (string - required) The state property you want to sync with Firebase
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.
    • then: (function - optional) The callback function that will be invoked when the initial listener is established with Firebase. Typically used (with syncState) to change this.state.loading to false.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.syncState(`shoppingList`,{context: this,state: 'items',asArray: true});}addItem(newItem){this.setState({items: this.state.items.concat([newItem])//updates Firebase and the local state});}

bindToState(endpoint, options)

Purpose

One way data binding from Firebase to your component's state. Allows you to bind a component's state property to a Firebase endpoint so whenever that Firebase endpoint changes, your component's state will be updated with that change.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like your component's state property to listen for changes
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • state: (string - required) The state property you want to sync with Firebase
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.bindToState('tasks',{context: this,state: 'tasks',asArray: true});}

listenTo(endpoint, options)

Purpose

Allows you to listen to Firebase endpoints without binding those changes to a state property. Instead, a callback will be invoked with the newly updated data.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint which contains the data with which you'd like to invoke your callback function
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • then: (function - required) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

An object which you can pass to removeBinding when your component unmounts to remove the Firebase listeners.

Example

componentDidMount(){base.listenTo('votes',{context: this,asArray: true,then(votesData){vartotal=0;votesData.forEach((vote,index)=>{total+=vote});this.setState({total});}})}

fetch(endpoint, options)

Purpose

Allows you to retrieve the data from a Firebase endpoint just once without subscribing or listening for data changes.

Arguments

  1. endpoint - type: string - The relative Firebase endpoint which contains the data you're wanting to fetch
  2. options - type: object - properties:
    • context: (object - required) The context of your component
    • asArray: (boolean - optional) Returns the Firebase data at the specified endpoint as an Array instead of an Object
    • then: (function - required) The callback function that will be invoked with the data from the specified endpoint when the endpoint changes
    • queries: (object - optional) Queries to be used with your read operations. See Query Options for more details.

Return Value

No return value

Example

getSales(){base.fetch('sales',{context: this,asArray: true,then(data){console.log(data);}});}

post(endpoint, options)

Purpose

Allows you to update a Firebase endpoint with new data. Replace all the data at this endpoint with the new data

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like to update with the new data
  2. options - type: object - properties:
    • data: (any - required) The data you're wanting to persist to Firebase
    • then: (function - optional) A callback that will get invoked once the new data has been saved to Firebase

Return Value

No return value

Example

addUser(){base.post(`users/${userId}`,{data: {name: 'Tyler McGinnis',age: 25},then(){Router.transitionTo('dashboard');}});}

push(endpoint, options)

Purpose

Allows you to add data to a Firebase endpoint. Adds data to a child of the endpoint with a new Firebase push key

Arguments

  1. endpoint - type: string - The relative Firebase endpoint that you'd like to push the new data to
  2. options - type: object - properties:
    • data: (any - required) The data you're wanting to persist to Firebase
    • then: (function - optional) A callback that will get invoked once the new data has been saved to Firebase

Return Value

A Firebase reference for the generated location

Example

addBear(){base.push('bears',{data: {name: 'George',type: 'Grizzly'},then(){Router.transitionTo('dashboard');}});}

removeBinding(ref)

Purpose

Remove the listeners to Firebase when your component unmounts.

Arguments

  1. ref - type: Object - The return value of syncState, bindToState, or listenTo

Return Value

No return value

Example

componentDidMount(){this.ref=base.syncState('users',{context: this,state: 'users'});}componentWillUnmount(){base.removeBinding(this.ref);}

reset()

Purpose

Removes every Firebase listener and resets all private variables. Used for testing purposes.

Arguments

No Arguments

Return Value

No return value


Use the query option to utilize the Firebase Query API. For a list of available queries and how they work, see the Firebase docs.

Queries are accepted in the options object of each read method (syncState, bindToState, listenTo, and fetch). The object should have one or more keys of the type of query you wish to run, with the value being the value for the query. For example:

base.syncState('users',{context: this,state: 'users',asArray: true,queries: {orderByChild: 'iq',limitToLast: 3}})

The binding above will sort the users endpoint by iq, retrieve the last three (or, three with highest iq), and bind it to the component's users state. NOTE: This query is happening within Firebase. The only data that will be retrieved are the three users with the highest iq.

re-base exposes Firebase's web clientauthWithPassword, authWithCustomToken, authWithOAuthPopup, authWithOAuthRedirect, authWithOAuthToken methods to allow user authentication. getAuth is also exposed to access the current authentication state.

// Simple email authenticationbase.authWithPassword({email : 'bobtony@firebase.com',password : 'correcthorsebatterystaple'},authHandler);// Authentication via a custom authentication tokenbase.authWithCustomToken(token,authHandler);// Authentication via OAuth providers ("facebook", "github", "google", or "twitter")base.authWithOAuthPopup("<provider>",authHandler);base.authWithOAuthRedirect("<provider>",authHandler);base.authWithOAuthToken("<provider>",token,authHandler);// Log a user outbase.unauth()// Get authentication informationvarauthData=base.getAuth();
// Listen to authenticationfunctionauthDataCallback(authData){if(authData){console.log("User "+authData.uid+" is logged in with "+authData.provider);}else{console.log("User is logged out");}}varref=newFirebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");ref.onAuth(authDataCallback);

re-base exposes createUser, removeUser, resetPassword and changePassword methods for user management.

// Createbase.createUser({email: 'bobtony@firebase.com',password: 'correcthorsebatterystaple'},userHandler);// Removebase.removeUser({email: 'bobtony@firebase.com',password: 'correcthorsebatterystaple'},errorHandler);// Reset Passwordbase.resetPassword({email: 'bobtony@firebase.com'},errorHandler);// Change Passwordbase.changePassword({email: 'bobtony@firebase.com',oldPassword: 'correcthorsebatterystaple',newPassword: 'chipsahoy'},errorHandler);

Contributing

  1. npm install
  2. Edit src/rebase.js
  3. Add/edit tests in tests/specs/re-base.spec.js
  4. npm run build
  5. npm run test

Credits

re-base is inspired by ReactFire from Firebase. Jacob Turner is also a core contributor and this wouldn't have been possible without his assistance.

License

MIT

About

🔥 A Relay inspired library for building React.js + Firebase applications. 🔥

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages