0.0.2 • Published 7 years ago
firebase-react-redux v0.0.2
firebase-react-redux
This lib focus on binding your redux state to your firebase backend. We do this with a component based approach so that all fetch/sync/unsync operations are done when a component of yours is mounted or unmounted.
We provide a single FBSync
component that you may use directly or by wrapping it with a predefined setup and exporting it as your own component. We recommended that you use the latter for a more scalable application.
Examples
direct use - for getting your feet wet
import React from 'react';
import FBSync from 'firebase-react-redux';
import { connect } from 'react-redux';
const MyPosts = ({ myPosts }) => (
<section>
// syncs all posts
// saves them as an array of objects ordered by the 'updatedAt' prop
<FBSync
path='myPosts'
orderBy='updatedAt' />
{myPosts.map((post) => {
<article>
<h1>{post.title}</h1>
<time>{post.updatedAt}</time>
<p>{post.body}</p>
</article>
})}
</section>
)
export default connect((state) => {
myPosts: state.fb.myPosts
})(MyPosts);
wrapped - for scalable applications
// syncs post object
const FBPost = ({ postId }) => (
<FBSync path={`posts/${postId}`} />
)
// fetches an user only if not already on state
// if fetch was set to 'hard' or true we would always fetch it from the database
const FBUser = ({ userId }) => (
<FBSync fetch='soft' path={`users/${userId}`} />
)
const Post = ({ postId, post, user }) => (
<article>
<FBPost postId={postId} />
{(!post) && (
<p>loading…</p>
)}
{(post) && (
<div>
<FBUser userId={post.createdBy} />
<h1>{post.title}</h1>
<author>{user ? user.name : 'loading…'}</author>
<p>{post.body}</p>
</div>
)}
</article>
)
export default connect((state, props) => {
const post = state.fb.posts[props.postId];
return {
post: post,
user: post && state.fb.users[post.createdBy]
};
})(Post);
Setup
Just add our reducer to your rootReducer and optionally pass in a custom binding for immutable states.
mutable
import { combineReducers } from 'react-redux';
import { firebaseReactReduxReducer } from 'firebase-react-redux';
combineReducers(
…,
fb: firebaseReactReduxReducer()
)
immutable
import { combineReducers } from 'react-redux';
import { firebaseReactReduxReducer, firebaseReactReduxImmutable } from 'firebase-react-redux';
combineReducers(
…,
fb: firebaseReactReduxReducer(firebaseReactReduxImmutable)
)