Giter Club home page Giter Club logo

react-firestore's Introduction

Build Status codecov MIT License version

size gzip size module formats: umd, cjs, and es

react-firestore 🔥🏪

React components to fetch collections and documents from Firestore

The problem

You want to use the new Firestore database from Google, but don't want to have to use redux or any other state management tool. You would like to not have to worry too much about the exact API for firestore (snapshots, references, etc), and just be able to retrieve collections and documents and read their data.

You also want to do all this using render props, because they're awesome.

The solution

This is a set of components that allows you to interact with Firestore collections and documents, without needing to constantly call additional methods (like .data()) to display your data.

There is still an escape hatch where the snapshot from Firestore is provided to your render function, in the event that you need more control over your interactions with Firestore.

Disclaimer

This project is still a work in progress and in an alpha state. The API may update frequently.

Table of Contents

Installation

This package is available on npm.

npm install --save react-firestore

Or, if you're using yarn:

yarn add react-firestore

Usage

There are 3 components provided with this package:

FirestoreProvider

This component allows the FirestoreCollection and FirestoreDocument components to communicate with Firestore.

At the top level of your app, configure firebase and render the FirestoreProvider component.

If you're using create-react-app, your index.js file would look something like this:

import React from 'react';
import ReactDOM from 'react-dom';
import firebase from '@firebase/app';
import '@firebase/firestore';
import { FirestoreProvider } from 'react-firestore';

import App from './App';

const config = {
  apiKey: '<your_api_key>',
  projectId: '<your_firebase_project_id>',
};

firebase.initializeApp(config);

ReactDOM.render(
  <FirestoreProvider firebase={firebase}>
    <App />
  </FirestoreProvider>,
  document.getElementById('root'),
);

Important: Starting with Firebase v5.5.0 timestamp objects stored in Firestore get returned as Firebase Timestamp objects instead of regular Date() objects. To make your app compatible with this change, add the useTimestampsInSnapshots to the FirestoreProvider element. If you dont do this your app might break. For more information visit [the Firebase refrence documentation][https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp].

Note: The reason for the separate imports for @firebase/app and @firebase/firestore is because firestore is not included in the default firebase wrapper package. See the firestore package for more details.

FirestoreProvider props

firebase

firebase | required

An already initialized firebase object from the @firebase/app package.

FirestoreCollection

This component allows you to interact with a Firestore collection. Using this component, you can access the collection at a given path and provide sort options, perform queries, and paginate data.

This component will setup a listener and update whenever the given collection is updated in Firestore.

Example usage to get a collection and sort by some fields:

<FirestoreCollection
  path="stories"
  sort="publishedDate:desc,authorName"
  render={({ isLoading, data }) => {
    return isLoading ? (
      <Loading />
    ) : (
      <div>
        <h1>Stories</h1>
        <ul>
          {data.map(story => (
            <li key={story.id}>
              {story.title} - {story.authorName}
            </li>
          ))}
        </ul>
      </div>
    );
  }}
/>

FirestoreCollection props

path

string | required

The / separated path to the Firestore collection. Collections must contain an odd number of path segments.

sort

string | defaults to null

A comma-delimited list of fields by which the query should be ordered. Each item in the list can be of the format fieldName or fieldName:sortOrder. The sortOrder piece can be either asc or desc. If just a field name is given, sortOrder defaults to asc.

limit

number | defaults to null

The maximum number of documents to retrieve from the collection.

filter

array or array of array | defaults to null

Passing in an array of strings creates a simple query to filter the collection by

<FirestoreCollection
  path={'users'}
  filter={['firstName', '==', 'Mike']}
  render={() => {
    /* render stuff*/
  }}
/>

Passing in an array of arrays creates a compound query to filter the collection by

<FirestoreCollection
  path={'users'}
  filter={[['firstName', '==', 'Mike'], ['lastName', '==', 'Smith']]}
  render={() => {
    /* render stuff*/
  }}
/>

Passing in document references allows you to filter by reference fields:

<FirestoreCollection
  path={'users'}
  filter={[
    'organization',
    '==',
    firestore.collection('organizations').doc('foocorp'),
  ]}
  render={() => {
    /* render stuff*/
  }}
/>
render

function({}) | required

This is the function where you render whatever you want based on the state of the FirebaseCollection component. The object provided to the render function contains the following fields:

property type description
isLoading boolean Loading status for the firebase query. true until an initial payload from Firestore is received.
error Error Error received from firebase when the listen fails or is cancelled.
data Array<any> An array containing all of the documents in the collection. Each item will contain an id along with the other data contained in the document.
snapshot QuerySnapshot / null The firestore QuerySnapshot created to get data for the collection. See QuerySnapshot docs for more information.

FirestoreDocument

This component allows you to retrieve a Firestore document from the given path.

This component will setup a listener and update whenever the given document is updated in Firestore.

<FirestoreDocument
  path="stories/1"
  render={({ isLoading, data }) => {
    return isLoading ? (
      <Loading />
    ) : (
      <div>
        <h1>{data.title}</h1>
        <h2>
          {data.authorName} - {data.publishedDate}
        </h2>
        <p>{data.description}</p>
      </div>
    );
  }}
/>

FirestoreDocument props

path

string | required

The / separated path to the Firestore document.

render

function({}) | required

This is the function where you render whatever you want based on the state of the FirebaseDocument component. The object provided to the render function contains the following fields:

property type description
isLoading boolean Loading status for the firebase query. true until an initial payload from Firestore is received.
error Error Error received from firebase when parsing the document data.
data Object / null The document that resides at the given path. Will be null until an initial payload is received. The document will contain an id along with the other data contained in the document.
snapshot DocumentSnapshot / null The firestore DocumentSnapshot created to get data for the document. See DocumentSnapshot docs for more information.

Firestore

This component supplies the firestore database to the function specified by the render prop. This component can be used if you need more flexibility than the FirestoreCollection and FirestoreDocument components provide, or if you would just rather interact directly with the firestore object.

<Firestore
  render={({ firestore }) => {
    // Do stuff with `firestore`
    return <div> /* Component markup */ </div>;
  }}
/>

Firestore props

render

function({}) | required

This is the function where you render whatever you want using the firestore object passed in.

property type description
firestore Object The Firestore class from firestore. See the docs for the Firestore class for more information.

withFirestore

This higher-order component can be used to provide the firestore database directly to the wrapped component via the firestore prop.

class MyComponent extends Component {
  state = {
    story: null,
  };

  componentDidMount() {
    const { firestore } = this.props;

    firestore.doc('stories/1').onSnapshot(snapshot => {
      this.setState({ story: snapshot });
    });
  }

  render() {
    const { story } = this.state;
    const storyData = story ? story.data() : null;

    return storyData ? (
      <div>
        <h1>{storyData.title}</h1>
        <h2>
          {storyData.authorName} - {storyData.publishedDate}
        </h2>
        <p>{storyData.description}</p>
      </div>
    ) : (
      <Loading />
    );
  }
}

export default withFirestore(MyComponent);

Component.WrappedComponent

The wrapped component is available as a static property called WrappedComponent on the returned component. This can be used for testing the component in isolation, without needing to provide context in your tests.

Props for returned component

wrappedComponentRef

function | optional

A function that will be passed as the ref prop to the wrapped component.

react-firestore's People

Contributors

aaaronmf avatar bfirsh avatar damonbauer avatar drobannx avatar green-arrow avatar hartym avatar lucacasonato avatar mikekellyio avatar peternoordijk avatar sampl avatar tomsun avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-firestore's Issues

Unknown relation: !=

  • react-firestore version: 0.10.3

I want to show all elements in a list, which has not an empty string.

This works, it shows me only empty Strings
filter={['name', '==', '']}

But this doesn't I'm getting: INTERNAL ASSERTION FAILED: Unknown relation: !=
filter={['name', '!=', '']}

Typescript support

If someone (me or anyone else) would like to add Typescript support to react-firestore, would you prefer:

  1. the whole project to be migrated to Typescript, or
  2. an independent type definition to be maintained via DefinitelyTyped.

From a TS user perspective the solution 1/ is preferable since it prevents type definition to drift appart from actual library but it requires that the library is maintained in TS (which has numerous benefits :))

👋

FirestoreDocument is returning data from an id that doesn't exist

  • react-firestore version: 0.8.1 (from getfirefly.org)
  • node version: 12.13.1
  • npm (or yarn) version: 6.13.6

Relevant code or config

<FirestoreDocument path={`posts/${match.params.id}`}>

What you did: Query a document with an id that doesn't exist.

What happened:

Instead of getting an error (necessary for displaying a 404), it just returns the data with the id I provided it.
Screen Shot 2020-06-29 at 5 33 12 PM

Suggested solution: Provide an error when the document isn't found.

Make use of docChange of QuerySnapshot to pick changes

Is there an option for react-firebase to support delta change of QuerySnapshot to cherry-pick and update only the affected documents (added, modified, deleted) in the local copy?

  • react-firestore version: 1.0.1
  • node version: v8.16.0
  • npm (or yarn) version: 1.19.1

Relevant code or config

The current FirebaseCollection.handleOnSnapshotSuccess() is directly updating the state by replacing the data in case of even minor updates of the collection.

What you did:
MUI-Datatable wrapped in FirebaseCollection and data is shared between the components.

What happened:
Upon internal (from within the app) or external change of the data (another app user) the Datatable widget will re-render fully.

Problem description:
In case consumer widget is relying on state of data the component must re-render fully breaking the flow unexpectedly. In my app the FirebaseCollection feeds MUI-Datatable and change of underlying data re-renders the full table and loosing the state of the table.

Suggested solution:

  • Use docChange() and a different state management approach,
  • useReducer to delegate state management to consumer,
  • any other option?

Add `withFirestore` component

Add a withFirestore component that will inject the firestore database (from firebase.firestore()) into a component.

This provides an escape hatch that will allow the user to directly access firestore in cases where the other components don't completely fulfill the user's needs.

Support for firebase emulator

Is anyone working on adding support for the local firebase emulator? I would like to be able to pass prop to indicate I want tp connect to the local firestore emulator for local testing and CI/CD scripts.

Listener not updated if props change

  • react-firestore version: 0.6.0
  • node version: 8.9.0
  • npm (or yarn) version: 5.5.1

Relevant code or config

<FirestoreCollection
  path="leagues"
  render={({ isLoading, data }) => {
    return isLoading ? (
      <Loading />
    ) : (
      <div className="form-group">
        <label htmlFor="leagueId">League</label>
        <select
          className="form-control"
          name="leagueId"
          value={this.state.leagueId}
          onChange={this.updateVal}
        >
          <option value="">Please select a league...</option>
          {data &&
            data.map(league => (
              <option key={league.id} value={league.id}>
                {league.name}
              </option>
            ))}
        </select>
      </div>
    );
  }}
/>

<FirestoreCollection
  path="teams"
  filter={["leagueId", "==", this.state.leagueId]}
  render={({ isLoading, data }) => {
    return isLoading ? (
      <Loading />
    ) : (
      <div className="form-group">
        <label htmlFor="teamId">Team</label>
        <select
          className="form-control"
          name="teamId"
          value={this.state.teamId}
          onChange={this.updateVal}
        >
          <option value="">Please select a team...</option>
          {data &&
            data.map(team => (
              <option key={team.id} value={team.id}>
                {team.name}
              </option>
            ))}
        </select>
      </div>
    );
  }}
/>

What you did:
I have 2 form elements. When the user selects a league, I want the team select to update with that particular leagues teams.

What happened:
The team dropdown never updates to reflect leagueId changes because the FirestoreCollection listener is only set up on mount, instead of prop change.

Reproduction repository:

Problem description:

Suggested solution:
FirestoreCollection and FirestoreDocument should be refactored to update on prop change.

Guide how to combine collections

Hi @green-arrow, this is a truly awesome project!

I wanted to ask, is there any place in the docs which would guide me towards combining collections?

For instance, in the case where I have two collections. One has property 'collection1.userId' and collection 2 also contains this: 'collection2.userId'.

I would like to query all of collection1 and combine to each document, the matching document from collection2.

In super rough pseudo code, the idea is:

   FirestoreCollection='users'
    userId
       firstName
       lastName
    FirestoreCollection='relational-collection'
       userId=='userId' 
          get related document

Add timeout prop to stop loading indefinitely

  • react-firestore version: @latest
  • node version: 10.1.0
  • npm (or yarn) version: @latest

Great work with the library 👍 . Currently using with react-native-firebase. Not sure if my issue is related only to mobile but, I am not able to perform a .where in conjunction with a .order and have the collections listen to real time updates.. No problem, I've decided to just do my sorting in my components..

It would be nice to add in a sort prop to clean up this logic that gets applied after receiving a collection so I don't have to do this as well.

The biggest issue with this is currently there is no way to stop showing the loading after some timeout. If there is not data in a collection this loads indefinitely.. which isn't the best UX. We should be able to provide a timeout to stop showing the loading after a certain amount of time (while still having it listen to updates come in). I have a solution that works just fine, but it would be nice to just have this here in this module.

I'd be willing to create a PR for this if you think both or one of these suggestions would be beneficial.

Let me know!

Option to pass loading component

Another feature request--would be really nice to have the option to pass a loading component directly to the react-firestore components.

This could co-exist with the current method of passing isLoading in the render method, letting people choose.

// CURRENT

<FirestoreCollection
  path="stories"
  sort="publishedDate:desc,authorName"
  render={({ isLoading, data }) => {
    return isLoading ? (
      <Loading />
    ) : (
      <div>
        <h1>Stories</h1>
        <ul>
          {data.map(story => (
            <li key={story.id}>
              {story.title} - {story.authorName}
            </li>
          ))}
        </ul>
      </div>
    );
  }}
/>


// PROPOSED

<FirestoreCollection
  path="stories"
  sort="publishedDate:desc,authorName"
  loading={Loading}
  render={({ data }) => (
    <div>
      <h1>Stories</h1>
      <ul>
        {data.map(story => (
          <li key={story.id}>
            {story.title} - {story.authorName}
          </li>
        ))}
      </ul>
    </div>
  )}
/>

To make the API even cleaner, you could let users set a default loading component so it only has to be passed in special cases (similar solution).

// user component (no loading code at all)
<FirestoreCollection
  path="stories"
  sort="publishedDate:desc,authorName"
  render={({ data }) => (
    <div>
      <h1>Stories</h1>
      <ul>
        {data.map(story => (
          <li key={story.id}>
            {story.title} - {story.authorName}
          </li>
        ))}
      </ul>
    </div>
  )}
/>

// FirestoreCollection component
render() {
  if (this.state.loading) {
    return this.props.loading || 'loading...' // or replace 'loading...' with a user-set global default loading component
  }
  ...
}

Hopefully these are useful suggestions! Let me know if I should format differently or hold off submitting until I have a PR.

How to paginate?

  • react-firestore version: 0.10.3

FirestoreCollection

This component allows you to interact with a Firestore collection. Using this component, you can access the collection at a given path and provide sort options, perform queries, and paginate data.

What would be the idiomatic way of paginating? limit is exposed, but I don't see startAt or startAfter in the interface of <FirestoreCollection>
https://firebase.google.com/docs/firestore/query-data/query-cursors

Thanks for providing a nice library!

Support for firebase emulator

Is anyone working on adding support for the local firebase emulator? I would like to be able to pass prop to indicate I want tp connect to the local firestore emulator for local testing and CI/CD scripts.

Add support for pagination

Allow the user to specify the total number of documents that should be returned, as well as an offset, so that the user can support paging through a large number of documents.

New timestamp config throwing error on init

  • react-firestore version: 0.10.1
  • firebase version: 5.5.8
  • node version: 8
  • npm (or yarn) version: 1.7 yarn

Relevant code or config

import firebase from '@firebase/app';
import '@firebase/firestore';
firebase.initializeApp(firebaseConfig);
<FirestoreProvider firebase={firebase} useTimestampsInSnapshots>

What you did:
It seems like the latest version of the package isn't initialising correctly due to how the timestamp settings are being set.

What happened:
Throwing the following error on load:

Firebase: firebase.firestore() takes either no argument or a Firebase App instance. (app/invalid-app-argument).
image

Suggested solution:
It seems to be caused by this line: https://github.com/green-arrow/react-firestore/blob/master/src/FirestoreProvider.js#L27

Untested, but I think it needs to be replaced with firebase.firestore().settings({ timestampsInSnapshots: this.props.useTimestampsInSnapshots}) before Line 26

Errors from queries

Sorry for not using the issue template... I just have a really small question. I'm using the library for some queries and stuff and I wanted to show a message when an error popped up. I noticed this awesome commit of like 12 days ago which solves this issue and I wonder when this will be deployed to NPM and everything. Thanks!

firestoreDatabase children prop is null because firestore().settings() does not return firestore instance

Versions

Relevant code or config (meta code)

let firebase = ...;
export default () => (
    <FirestoreProvider firebase={firebase}>
        <FirestoreCollection path={'mycollection'} ... />
    </FirestoreProvider>
)

What you did:

Following the readme instructions basically to simply render a FirestoreCollection somewhere under the FirestoreProvider.

What happened:

Blank screen, complaining for firestoreDatabase childProp being null although it's required.

Problem description:

Apparently, firebase's firestore api now returns null from the settings(...) call (which I guess was wrong before a certain version.

See https://github.com/firebase/firebase-js-sdk/blob/master/packages/firestore-types/index.d.ts#L96

Suggested solution:

Instead of returning from the .settings() call, just do it on its own line and return the firestore instance.

https://github.com/green-arrow/react-firestore/blob/master/src/FirestoreProvider.js#L28

(fix works locally when patching the provider code, will provide a simple pull request)

Component to provide Firebase Auth

I know this isn't a Firestore request, but I'm guessing a lot of people who use this package would appreciate a component with a similar API to expose the state of Firebase Auth. (I know I would.)

Sample usage:

import { FirebaseAuth } from 'react-firestore'

<FirebaseAuth>
  { ({error, isLoading, auth}) => {
    if (error) {
      return 'error logging you in'
    }
    if (isLoading) {
      return 'loading account...'
    }
    if (!auth) {
      return <LoginButton />
    } else {
      return <UserSummary user={auth} />
    }
  }}
</FirebaseAuth>

Something like this could work: https://github.com/sampl/firefly/blob/master/src/data/AuthProvider.js

What do you think @green-arrow?

Please add @types/react-firestore declarations to make it clearer the types of each element in the library

  • react-firestore version: 1.0.1
  • node version: 10.16.0
  • npm (or yarn) version: 6.8.0

I use react together with typescript, for ease of typing and being native (I use VS Code) when comparing with Flow. It would be interesting to create a index.d.ts file containing the declared types of the library, so that it would be possible to make the most of the resources being created ...

I searched the types defined for the library but did not find it. I also searched within the repository itself and did not find it. I believe that if they were created, it would be possible to work more easily and clearly ...

Big scary console error

I'm observing the following console error which appears to be coming from react-firestore:

index.js:2178 [2018-05-09T08:43:10.595Z]  @firebase/firestore: Firestore (4.13.0): 
The behavior for Date objects stored in Firestore is going to change
AND YOUR APP MAY BREAK.
To hide this warning and ensure your app does not break, you need to add the
following code to your app before calling any other Cloud Firestore methods:

  const firestore = firebase.firestore();
  const settings = {/* your settings... */ timestampsInSnapshots: true};
  firestore.settings(settings);

With this change, timestamps stored in Cloud Firestore will be read back as
Firebase Timestamp objects instead of as system Date objects. So you will also
need to update code expecting a Date to instead expect a Timestamp. For example:

  // Old:
  const date = snapshot.get('created_at');
  // New:
  const timestamp = snapshot.get('created_at');
  const date = timestamp.toDate();

Please audit all existing usages of Date when you enable the new behavior. In a
future release, the behavior will change to the new behavior, so if you do not
follow these steps, YOUR APP MAY BREAK.

Accept Number as valid type for filter array

Currently using a number to filter a collection query causes a PropType error, when it is actually valid. In fact, changing the number to a string to silence the warning breaks the filter.

I'm happy to contribute the fix for this, if you can confirm that this project is still being maintained? Hope so!

Expose Firestore query errors

First of all, thanks for releasing react-firestore. It's the perfect way to bring my two favorite tools together, and the API you chose is spot on.

A feature request: it would be great if each component could pass Firebase errors when they occur. This can happen if you try to query content but don't have the right permissions, for example.

Something like:

<FirestoreCollection
  path="stories"
  sort="publishedDate:desc,authorName"
  render={({ isLoading, data, error }) => {
    if (error) return `Whoops! ${error.message}`
    
    return isLoading ? (
      <Loading />
    ) : (
      <div>
        <h1>Stories</h1>
        <ul>
          {data.map(story => (
            <li key={story.id}>
              {story.title} - {story.authorName}
            </li>
          ))}
        </ul>
      </div>
    );
  }}
/>

I've built something similar here: https://github.com/sampl/firefly/blob/master/src/data/PostsProvider.js

Render to children instead of "render" prop

Last one I promise :)

This one is really a matter of opinion, but I think rendering to this.props.children instead of a "render" prop makes things a little cleaner.

The React docs describe using this method: https://reactjs.org/docs/render-props.html#using-props-other-than-render

Just my 2¢

// CURRENT

<FirestoreCollection
  path="stories"
  sort="publishedDate:desc,authorName"
  render={({ isLoading, data }) => {
    return isLoading ? (
      <Loading />
    ) : (
      <div>
        <h1>Stories</h1>
        <ul>
          {data.map(story => (
            <li key={story.id}>
              {story.title} - {story.authorName}
            </li>
          ))}
        </ul>
      </div>
    );
  }}
/>


// PROPOSED

<FirestoreCollection path="stories" sort="publishedDate:desc,authorName">
  {({ isLoading, data }) => {
    return isLoading ? (
      <Loading />
    ) : (
      <div>
        <h1>Stories</h1>
        <ul>
          {data.map(story => (
            <li key={story.id}>
              {story.title} - {story.authorName}
            </li>
          ))}
        </ul>
      </div>
    );
  }}
</FirestoreCollection>

Query a random document

  • react-firestore version: @latest
  • node version: 8.11.1
  • npm (or yarn) version: 6.0.0

Relevant code or config:
n/a

I was just wondering if there was a way to query a random document?

FirestoreDocument should handle document not existing

If the document does not exist, you get this in data: {id: "undefined"} (yes, the string "undefined", not the identifier!). This makes it rather difficult to check.

I would expect data just to be null if the document does not exist.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.