Giter Site home page Giter Site logo

prescottprue / redux-firestore Goto Github PK

View Code? Open in Web Editor NEW
579.0 15.0 111.0 7.1 MB

Redux bindings for Firestore

License: MIT License

JavaScript 99.96% Shell 0.04%
firestore redux redux-middleware redux-enhancer firebase react react-redux react-redux-firebase

redux-firestore's Introduction

redux-firestore

Redux bindings for Firestore. Provides low-level API used in other libraries such as react-redux-firebase

NPM version NPM downloads License Code Style Build Status Code Coverage semantic-release

Gitter

Installation

npm install redux-firestore --save

This assumes you are using npm as your package manager.

If you're not, you can access the library on unpkg, download it, or point your package manager to it. Theres more on this in the Builds section below

Complementary Package

Most likely, you'll want react bindings, for that you will need react-redux-firebase. You can install the current version it by running:

npm install --save react-redux-firebase

react-redux-firebase provides withFirestore and firestoreConnect higher order components, which handle automatically calling redux-firestore internally based on component's lifecycle (i.e. mounting/un-mounting)

Overview

API Quick Start

Load data

Construct a Firestore query, attach listeners for updates and get the data from the selector.

const MyController = () => {
  // 1. construct query
  const taskQuery = {
    collection: `workspace/MySpace/tasks`,
    where:[
      ['status', '<', 1],
      ['deleted', '==', false]
    ],
    orderBy: ['createdAt', 'desc'],
    storeAs: 'tasksStarted',
  }
  
  // 2. load & attached listeners for document changes
  useFirestoreConnect([taskQuery]);

  // 3. Get results
  const tasks = useSelector(state => 
    state.firestore.cache['tasksStarted'].docs
  );
  
  // 4. Display when the data returns
  return (<ol>
    {tasks && tasks.map(({id, title}) => (
      <li key={id}>title</li>
    ))}
  </ol>);
};

Saving Data

Use redux-firestore's mutate function to queue changes to Firestore and see the optimitic results instantly in the UI.

const MyController = (task) => {
  const changeTitle = useCallback(({id, path, title}) => {
    dispatch(
      createMutate({
        doc: id, 
        collection: path, 
        title
      }))
      .catch((error) => { alert(error) });
  })
  
  return (<TaskView onSave={changeTitle} />);
};

Roadmap

  • Automatic support for documents that have a parameter and a subcollection with the same name (currently requires storeAs)
  • Support for Passing a Ref to setListener in place of queryConfig object or string

Post an issue with a feature suggestion if you have any ideas!

redux-firestore's People

Contributors

alexmattson avatar alvinthen avatar am17torres avatar bcgilliom avatar compojoom avatar danleavitt0 avatar demoran23 avatar dependabot[bot] avatar diagramatics avatar epilande avatar erikswed avatar fredrik-sogaard avatar gregfenton avatar itsmedmd avatar jareqpl avatar lynklody avatar nemo avatar prescottprue avatar renovate[bot] avatar rscotten avatar thiagovice avatar uloco 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  avatar  avatar  avatar

redux-firestore's Issues

firestore.add doesnt work

the following code throws the following error

firestore.add('/todos', { title: 'todosTitle' });

-->

FirebaseError: Function CollectionReference.doc() requires its first argument to be of type string, but it was: a custom Object object

So I think somewhere in the middle where we take the params and pass it to the internal method, we're messing something up.

UPDATE_SUCCESS not updating the data reducer

Do you want to request a feature or report a bug?
Bug

What is the current behavior?
We have 3 filtered views. When the page loads the user is presented with the first tab where we are filtering on state == 0 and we have a pagination.

The user is able to change the state to 1, then the UI should update and the item should be removed.

We use the update function and we are seeing 2 actions.
UPDATE_REQUEST
UPDATE_SUCCESS

the arguments for update_success show state == -1, but the actual data state doesn't change.
Once we get the UPDATE_SUCCESS a LISTENER_RESPONSE is dispatched and we get new items for the list. The problem here is that since our listener looks only for state == 0 and our changed item has state 1 - it's no longer in the LISTENER_RESPONSE and this item never gets modified in the state. So our UI still displays it.

What is the expected behavior?
UPDATE_SUCCESS - should update the item in the data reducer.

I looked at the code and see that you don't use UPDATE_SUCCESS in the data reducer? Why? Aren't we interested in single UPDATE_SUCCESS actions? Are we supposed to manually handle this in our reducers?

runs `npm run build` after installation

For some reason, installing redux-firestore will run npm run build immediately after installation. That results in the failure of the installation. I was trying to install it in a create-react-app project, and there was already a build script in my package.json. I temporarily removed that script from my package.json, and the install was successful. So I think that there's some sort of interference between the build script that redux-firestore calls, and the one that exists in the root project's package.json.

bug(core): store.firestore with all internal methods may cause performance issues

Do you want to request a feature or report a bug?
BUG - code added in 0.5.1 to enable other methods such as batch cased performance degredation

What is the current behavior?
All methods on firebase.firestore() are available on the store.firestore instance, but this causes performance issues if firestore is passed as a prop (as it is with withFirestore and firestoreConnect

What is the expected behavior?
Access to these methods should not impact performance of components that get firestore from store

Which versions of dependencies, and which browser are affected by this issue? Did this work in previous versions or setups?

  • v0.5.1 caused it
  • 0.5.0 and earlier do not have this issue

Steps to reproduce and if possible a minimal demo of the problem via codesandbox or similar.

Direct Firestore "add", "update", etc. calls fails when signed in

I've been updating a project of mine (which uses react-redux-firebase) from firebase to firestore.

So far so good. I've got the sign in system working, and have the data querying code working fine. (as far as I've tested anyway)

I'm now trying to reimplement the data saving/storing code. Because I prefer the direct route for storing data rather than the redux "action" system, I'm using code like this:

store.firebase.firestore().collection("users").add({
    first: "Ada",
    last: "Lovelace",
    born: 1815
}).then(()=>console.log("Done")).catch(err=>console.log("Error: " + err))

The code above works perfectly when I am not signed in. When I'm signed in, however, the code snippet does nothing. It just returns a promise which never completes.

If I sign back out, it starts working again. If I sign back in, it stops working.

Any idea what could be causing these direct calls to fail?

[bug] `LISTENER_RESPONSE` does not update `ordered`

Do you want to request a feature or report a bug?
bug

What is the current behavior?
When received action @@reduxFirestore/LISTENER_RESPONSE, the doc was already loaded and storeAs is set, only data got updated, not ordered.

image

What is the expected behavior?
Expect both ordered and data to be updated.

Which versions of dependencies, and which browser are affected by this issue? Did this work in previous versions or setups?

redux-firestore@^0.5:
  version "0.5.0"
react-redux-firebase@^2.1:
  version "2.1.0"

Steps to reproduce and if possible a minimal demo of the problem via codesandbox or similar.
Listener setup:

collection(pin): "discussions"
doc(pin): "5aed4e0740133e2af516db07"
storeAs(pin): "discussionById_5aed4e0740133e2af516db07"

Received action:

{
  type: '@@reduxFirestore/LISTENER_RESPONSE',
  meta: {
    collection: 'discussions',
    doc: '5aed4e0740133e2af516db07',
    storeAs: 'discussionById_5aed4e0740133e2af516db07'
  },
  payload: {
    data: {
      '5aed4e0740133e2af516db07': {
        text: '123',
        id: '5aed4e0740133e2af516db07',
      }
    },
    ordered: [
      {
        id: '5aed4e0740133e2af516db07',
        text: '123',
      }
    ]
  },
  merge: {}
}

RFF config:

  userProfile: 'users',
  attachAuthIsReady: true,
  presence: false,
  useFirestoreForProfile: true,
  logListenerError: true,
  oneListenerPerPath: true,
  enableLogging: true,

Failing test

      it.only('updates doc under storeAs', () => {
        action = {
          type: actionTypes.LISTENER_RESPONSE,
          meta: {
            collection: 'testing',
            doc: '123abc',
            storeAs: 'pathName',
          },
          payload: {
            ordered: [
              {
                content: 'new',
              },
            ],
          },
          merge: {},
        };

        state = {
          pathName: [
            {
              id: '123abc',
              content: 'old',
            },
          ],
        };
        expect(orderedReducer(state, action)).to.have.nested.property(
          `pathName.0.content`,
          'new',
        );
      });

Database data getting added at wrong path

The screenshot below should mostly explain it:

Basically, entries in the database are getting added at "users/USERID/USERID" -- instead of just "users/USERID". (ignore the correctly-added entry -- that is from a retrieval of the collection as a whole, which adds entries correctly without the extra wrapper)

I haven't yet determined what is causing the above issue to occur. It might be that I'm using the library incorrectly somewhere.

I will look into it, and find out what is causing the incorrect paths. Figured I would make an issue for it already, though, since the output above is still incorrect -- if from misuse, there should still probably be a catch/warning for it. (at the moment, it just happens silently)

Deleting object properties doesn't update the UI since 0.3.1

Do you want to request a feature or report a bug?

Bug

What is the current behavior?

If you have an object within a document, then deleting keys from that object doesn't update the firestore.data variable, however firestore.ordered is updated. This means the if the component uses firestore.data then the UI is not updated to reflect deleted keys. The database is correctly updated and refreshing the browser shows the expected values.

See https://codesandbox.io/s/m3jm3roko8 for an example.

In both 0.3.1 and <0.3.1 I can add an item and have it appear in the UI. The Redux diff looks like this for 0.3.1

image

and like this for 0.2.8

image

However when deleting items, 0.3.1 has this diff:

image

and 0.2.8 has this diff

image

Note that 0.3.1 only deletes the ordered value, but leaves the data value intact while 0.2.8 correctly deletes its data value and doesn't set an ordered value.

What is the expected behavior?

Values in firestore.data are updated to reflect the database value when object properties are deleted. This occurs as expected prior to 0.3.1.

Which versions of dependencies, and which browser are affected by this issue? Did this work in previous versions or setups?

See code sandbox

Steps to reproduce and if possible a minimal demo of the problem via codesandbox or similar.

https://codesandbox.io/s/m3jm3roko8

Hit the add and delete buttons. Notice that items are added correctly, but not removed when they are deleted. Hit refresh and the deleted items will go away.

It's a bit fiddly, but you can remove the redux-firestore dep and change it to 0.2.8 then refresh to try with the working version, although it sometimes takes a few tries to change the version.

The database looks like this if you want to create your own.

image

❀️

feat(query): subcollections of subcollections

Do you want to request a feature or report a bug?

Bug - Subcollections of subcollections not working on v0.3.*

compose(
  firestoreConnect((props) => {
    return [
      {
        collection: 'cities',
        doc: 'SF',
        subcollections: [
          {
            collection: 'zipcodes',
            doc: '123456',
            subcollections: [{collection: 'measurements', orderBy: ['date', 'desc'], limit: 1}],
          },
        ],
      },
    ];
  }),
  connect((state, props) => {
    return {
      client: get(state, 'firestore.data.cities.SF.zipcodes.123456'),
    };
  })
)

What is the current behavior?
Throws
"Error: Collection can only be run on a document. Check that query config for subcollection "otherThings" contains a doc parameter"

What is the expected behavior?

  1. This feature continues to be supported
  2. There is a test covering this so support remains in the future

Which versions of dependencies, and which browser are affected by this issue? Did this work in previous versions or setups?

  • 0.2.* - Works as expected
  • v0.3.* - Throws
    "Error: Collection can only be run on a document. Check that query config for subcollection "otherThings" contains a doc parameter"

Steps to reproduce and if possible a minimal demo of the problem via codesandbox or similar.

bug(orderedReducer): deleting an item from nested collection doesn't remove item from ordered reducer

Do you want to request a feature or report a bug?

Bug

What is the current behavior?

When calling delete:

this.props.firestore.delete(`feeds/${this.props.auth.uid}/questions/${this.state.currentQuestion.id}`);

I see the action being fired with the correct payload:
screen shot 2018-05-12 at 2 03 55 pm

And I see the data reducer showing null for the deleted item(s), but the ordered reducer still contains the deleted item(s):
screen shot 2018-05-12 at 2 03 06 pm

What is the expected behavior?

Calling delete should remove items from both the data and ordered reducers.

Which versions of dependencies, and which browser are affected by this issue? Did this work in previous versions or setups?

"react": "16.3.1",
"react-native": "0.55.3",
"react-native-firebase": "^4.0.4",
"react-redux": "^5.0.7",
"react-redux-firebase": "^2.1.1",
"redux": "^4.0.0",
"redux-firestore": "^0.5.1",

Steps to reproduce and if possible a minimal demo of the problem via codesandbox or similar.

bug(reducers): multiple subcollections on same parent collection causes invalid merge

Here's the scenario. This is React code with a router and I have two components on two different pages doing:

  firestoreConnect([
    { collection: 'group', doc: 'uJH3akkXRkje3ruPZ7au' },
    {
      collection: 'group',
      doc: 'uJH3akkXRkje3ruPZ7au',
      subcollections: [{ collection: 'objects' }],
    },
  ]),

And the other one doing

firestoreConnect(['group'])

Whenever I go from the first component to the second component,firestoreConnect on group would shallow merge the specific doc and removing the subcollection information stored in there, both on dataReducer and orderedReducer.

feat(query): both doc and subcollection within a single query

Do you want to request a feature or report a bug?
Bug

What is the current behavior?
I'm trying to request a collection and a subcollection:
{
collection: 'companies', doc: company,
subcollections: [{ collection: 'users' }]
}

What is the expected behavior?
the expected behavior is to receive the doc + a subcollection

Instead the subcollection overrides all properties of the doc. So one ends only with the subcollection data.

bug(query): Subcollections return an error

Do you want to request a feature or report a bug?
Bug

What is the current behavior?
Trying to get a subcollection produces the error:

Error: Collection can only be run on a document. Check that query config for subcollection: "details" contains a doc parameter.

What is the expected behavior?
The subcollection is retrieved

Which versions of dependencies, and which browser are affected by this issue? Did this work in previous versions or setups?
Current version, haven't used previous versions

Steps to reproduce and if possible a minimal demo of the problem via codesandbox or similar.
Use the following code to reproduce. I have also tried adding a document parameter to subcollection object without success.

componentWillMount() {
    
    const { firestore } = this.context.store;

    firestore.get({
      collection: 'users',
      document: 'bob',
      subcollections: [{ collection: 'details' }],
    });
}

Multiple where queries only applies last one

In utils/query.js when applying the where this code is setting newRef to the last where:

forEach(where, (whereArgs) => {
    if (!isArray(whereArgs)) {
      throw new Error(
        'Where currently only supports arrays. Each option must be an Array of arguments to pass to where.',
      );
    }
    newRef = whereArgs.length > 1 ? ref.where(...whereArgs) : ref.where(whereArgs);
}

I've tested a solution using reduce which I believe fixes this issue:

where.reduce((acc, whereArgs) => {
    if (!isArray(whereArgs)) {
      throw new Error(
        'Where currently only supports arrays. Each option must be an Array of arguments to pass to where.',
      );
    }
    return whereArgs.length > 1 ? acc.where(...whereArgs) : acc.where(whereArgs);
  }, ref);

Querying for a single doc in a collection fails from unexpected return type

Traced the codebase and it seems to have originated from somewhere around setListener at https://github.com/prescottprue/redux-firestore/blob/master/src/actions/firestore.js#L173.

Say I'm querying for a doc bar inside the foo collection. The snapshot returned by the Firestore reference would be a DocumentSnapshot instead of QuerySnapshot, meaning it would not have a .forEach() and would return null in dataByIdSnapshot or orderedFromSnap

Not sure if I'm missing something here. Instead of using firebase I used @firebase/app and @firebase/firestore for their separate ES bundles and also react-redux-firebase. Docs in Firestore have pointed to expecting a DocumentSnapshot instead of QuerySnapshot though.

bug(reducer): subcollections ordered awkwardly in state

suppose we have the following data schema:

root collection: todos

{
   title: String,
   completed: Boolean,
   todo_items: SubCollection
}

Therefore the path to todo_items of a collection with the ID: 6mjAkNg3XvB3v55LDIjy, will be: todos/6mjAkNg3XvB3v55LDIjy/todo_items.

When we have the following 2 firestoreConnect()s simultaneously, we are put in an awkward situation.

  • firestoreConnect(['/todos'])
  • firestoreConnect(['/todos/6mjAkNg3XvB3v55LDIjy/todo_items'])

In this situation, both of these connections try to store the collections under the same key: todos. Under firestore.data, they are conveniently nested. Therefore, a user can store subcollections of a document under the same key, without having to look for it somewhere else. This is actually really really cool.

The problem is under firestore.ordered. Once the subcollection is added, firestore.ordered loses the ordered list invariant. The data-structure becomes an array-object hybrid, and renders firestore.ordered unusable.

Creating a document no longer seems to update the dataReducer

I updated from 0.3.2 to 0.4.1 for the on deletion fix for the dataReducer however it appears to no longer push the new document to the store.

I can see that the document is successfully created in my firestore dashboard but I receive no new props, I do receive new props on document deletion and modification just not creation.

If I switch to the orderedReducer then it works as expected, it's also working perfectly fine with 0.3.2 which I have now reverted to.

Profile data in firestore

I've been using Firebase realtime database in my react-native app using react-redix-firebase and am switching to Firestore from RD. I have set the following for my reduxFirebase config:

const reduxFirebaseConfig = {
  userProfile: 'users',
  enableRedirectHandling: false,
  useFirestoreForProfile: true
}

but I user data still isn't being put in firestore when I use firebase.updateProfile and there is no firestore.updateProfile - Am I missing something??

bug(query): document updates to nested structures overwrite subcollections

Let's say we have the following schema:

{
   title: String,
   completed: Boolean,
   todo_items: SubCollection
}

Let's add the following firestoreConnect(['/todos'])

This will set store.firestore.data.todos to something like the following:

{
  'askldaskdadm123': {
    title: 'First todos list',
  },
  'omfnerfjknn103': {
    title: 'Second todos list',
  },
}

Now let's add the following: firestoreConnect(['/todos/6mjAkNg3XvB3v55LDIjy/todo_items'])
This will add the todo_items key to every todos list under store.firestore.data.todos, making it look like the following:

{
  'askldaskdadm123': {
    title: 'First todos list',
    todo_items: {
      'k3j2n42304': {
        title: 'first item under first list',
        completed: false,
      },
    },
  },
  'omfnerfjknn103': {
    title: 'Second todos list',
    todo_items: .....
  },
}

This is extremely convenient, but the data-structure will break when we update a todos list on the document level.

If we update the title of the second todos list to Something else, it will lose its todo_items, making store.firestore.data.todos look like the following:

{
  'askldaskdadm123': {
    title: 'First todos list',
    todo_items: {
      'k3j2n42304': {
        title: 'first item under first list',
        completed: false,
      },
    },
  },
  'omfnerfjknn103': {
    title: 'Something else',
  },
}

This is probably a reducer bug. When the snapshot of the todos list with an id: todosListId is received, I believe the reducer will automatically set store.firestore.todos[todosListId] to the value of that todos list, which will effectively overwrite the subcollections.

Instead, maybe we should first check if there's already some data in there, and then use the spread operator to only update with the new data.

Query with limit

Atm it is not possible to add a limit clause to a query, correct?

feat(query): support for populate on queries

Do you have any thought about making populate feature for this like in react-redux-firebase ?

While subcollection is good but based on the documentation said:
Limitations: You can't easily delete subcollections, or perform compound queries across subcollections.

Well if you want me to help i have some sample to make this work that i take from your pupulate.js file in react-redux-firebase with some additional features like:

  • nested object populate
  • populate as different child name using as property in populate object
  • populate object inside array

Just let me know if you're interested.

question(update): syntax to update document within subcollection not clear

Do you want to request a feature or report a bug?

Bug

What is the current behavior?

When I try to update a document within a subcollection, the change is performed on the subcollection, not the document itself.

The update statement:

this.props.firestore.update(`/artists/${this.props.artistId}/flights/${id}`, changes);

The @@reduxFirestore/UPDATE_REQUEST action object:

{
  meta: {
    collection: 'artists',
    doc: 'some-artist-id',
    subcollection: 'flights',
    other: ['some-flight-id']
  }
  payload: {
    args: [
      ...changes....
    ]
  }
}

What is the expected behavior?

I would expect the document within the subcollection to be updated, not the subcollection itself.

Which versions of dependencies, and which browser are affected by this issue? Did this work in previous versions or setups?

redux: 3.7.2
redux-firestore: 0.2.5
react-redux: 5.0.6
react-redux-firebase: 2.0.0-rc.2

[bug] Limit is ignored when the rest of query meta are the same

Do you want to request a feature or report a bug?
Bug

What is the current behavior?
Context:
Firstly, set listener { collection: 'book', limit: 3}
Later, set listener { collection: 'book', limit: 6}

Currently, the listener won't be updated. It remains to be { collection: 'book', limit: 3}. It also does not trigger the second query at all.

That's because limit is ignored when constructing listener name, code:

const { collection, doc, subcollections, where } = meta;

What is the expected behavior?
Expect it will trigger the second query. Either the listener will be updated to the most recent query { collection: 'book', limit: 6} or there will be two listeners.

Which versions of dependencies, and which browser are affected by this issue? Did this work in previous versions or setups?
v0.4.3

Steps to reproduce and if possible a minimal demo of the problem via codesandbox or similar.
As mentioned above.

store.firestore is set to the Firebase instance instead of firestoreInstance

Check out https://github.com/prescottprue/redux-firestore/blob/master/src/enhancer.js#L61

exports.default = function (firebaseInstance, otherConfig) {
  return function (next) {
    return function (reducer, initialState, middleware) {
      var store = next(reducer, initialState, middleware);

      var configs = _extends({}, _constants.defaultConfig, otherConfig);

      firestoreInstance = (0, _createFirestoreInstance2.default)(firebaseInstance.firebase_ || firebaseInstance, configs, store.dispatch);

      store.firestore = firebaseInstance;

      return store;
    };
  };
};

Notice how store.firestore is set to firebaseInstance. This has been the issue of why setListener was not available in store.firestore when using firestoreConnect.

orderBy don't return any results

Do you want to request a feature or report a bug?

Bug

What is the current behavior?

My query return expected results (but not ordered) without the orberBy and return an empty result with the orberBy.

try {
  const results = await firestore.get({
    collection: 'groups',
    where: [
      ['departureStation.id', '==', departureStationId],
      ['arrivalStation.id', '==', arrivalStationId],
      ['dateTime', '>=', startDate.toDate()],
      ['dateTime', '<=', endDate.toDate()],
    ],
    orderBy: ['dateTime', 'desc'],
  });
  console.log(results); // Return no result (results.empty === true)
} catch (err) {
  console.log(err);
}

But without, I have expected results:

try {
  const results = await firestore.get({
    collection: 'groups',
    where: [
      ['departureStation.id', '==', departureStationId],
      ['arrivalStation.id', '==', arrivalStationId],
      ['dateTime', '>=', startDate.toDate()],
      ['dateTime', '<=', endDate.toDate()],
    ],
    // orderBy: ['dateTime', 'desc'],
  });
  console.log(results); // Return expected results (results.empty === false)
} catch (err) {
  console.log(err);
}

What is the expected behavior?

Unless i'm mistaken, the orderBy should not affect the number of retrieved results but only their orders.

I do not know if there is a connection with #46.

Which versions of dependencies, and which browser are affected by this issue? Did this work in previous versions or setups?

{
    "firebase": "^4.8.2",
    "react": "^16.2.0",
    "react-dom": "^16.2.0",
    "react-redux": "^5.0.6",
    "react-redux-firebase": "^2.0.1",
    "redux": "^3.7.2",
    "redux-firestore": "^0.2.5",
}

All browsers seems to be affected.

Thanks a lot for your help :)

How to get to FieldValue?

I need access to FieldValue. How can I make this work?

const {firestore} = this.props
firestore.update({
      collection: 'userRegistrations',
      doc: documentId,
      {
          isLocked: true,
          lock: {
            owner: auth.uid,
            timestamp: firestore.FieldValue.serverTimestamp(),
          },
      }
    });

I can get it by importing firebase at the top of my file, and get it from there, but that seems a bit silly with the instance on props. And it would be easy to make a mistake with shadowing it.

TypeScript definitions for firestoreReducer

Do you want to request a feature or report a bug?
Reporting a bug

What is the current behavior?
Exception is thrown during compilation

What is the expected behavior?
A proper reducer is being created

Which versions of dependencies, and which browser are affected by this issue? Did this work in previous versions or setups?
0.3.2

Steps to reproduce and if possible a minimal demo of the problem via codesandbox or similar.

Having reducer as follows:

import { Reducer, combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import { firebaseReducer } from 'react-redux-firebase';
import { firestoreReducer } from 'redux-firestore';

const reducers: Reducer<ApplicationState> = combineReducers<ApplicationState>({
  firebase: firebaseReducer,
  firestore: firestoreReducer,
  router: routerReducer
});

export { reducers };

This throws compilation error because of firestoreReducer:

Argument of type '{ firebase: typeof firebaseReducer; firestore: typeof firestoreReducer; router: Reducer<RouterSta...' is not assignable to parameter of type 'ReducersMapObject'.
  Property 'firestore' is incompatible with index signature.
    Type 'typeof firestoreReducer' is not assignable to type 'Reducer<any>'.
      Type 'typeof firestoreReducer' provides no match for the signature '(state: any, action: AnyAction): any'.

Casting firebaseReducer as follows will fix it:

const reducers: Reducer<ApplicationState> = combineReducers<ApplicationState>({
  firebase: firebaseReducer,
  firestore: firestoreReducer as Reducer<ApplicationState>,
  router: routerReducer
});

bug: "Error: Listeners must be an Array of listener configs (Strings/Objects)"

I'm trying to get a basic working example using create-react-app, redux-firestore and react-redux-firebase. I've followed the Firestore Getting Started instructions and am getting the following error when viewing my app:

Error: Listeners must be an Array of listener configs (Strings/Objects)

on

ReactDOM.render(<AppContainer />, document.getElementById('root'))

where <AppContainer /> is:

const AppContainer = () => (
  <Provider store={store}>
    <App />
  </Provider>
);

and <App /> is a firestoreConnect HOC using:

export default compose(
  firestoreConnect({ collection: 'todos' }),
  connect((state, props) => ({
    todos: state.firestore.ordered.todos
  }))
)(App)

Full repo available at - https://github.com/brettdewoody/react-redux-firestore.

Here's the full error stack:

firestore.js:130 Uncaught Error: Listeners must be an Array of listener configs (Strings/Objects)
    at Object.setListeners (firestore.js:130)
    at Object.setListeners (actions.js:76)
    at FirestoreConnect.componentWillMount (firestoreConnect.js:73)
    at callComponentWillMount (react-dom.development.js:6370)
    at mountClassInstance (react-dom.development.js:6435)
    at updateClassComponent (react-dom.development.js:7840)
    at beginWork (react-dom.development.js:8225)
    at performUnitOfWork (react-dom.development.js:10224)
    at workLoop (react-dom.development.js:10288)
    at HTMLUnknownElement.callCallback (react-dom.development.js:542)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:581)
    at invokeGuardedCallback (react-dom.development.js:438)
    at renderRoot (react-dom.development.js:10366)
    at performWorkOnRoot (react-dom.development.js:11014)
    at performWork (react-dom.development.js:10967)
    at requestWork (react-dom.development.js:10878)
    at scheduleWorkImpl (react-dom.development.js:10732)
    at scheduleWork (react-dom.development.js:10689)
    at scheduleTopLevelUpdate (react-dom.development.js:11193)
    at Object.updateContainer (react-dom.development.js:11231)
    at react-dom.development.js:15226
    at Object.unbatchedUpdates (react-dom.development.js:11102)
    at renderSubtreeIntoContainer (react-dom.development.js:15225)
    at Object.render (react-dom.development.js:15290)
    at Object../src/index.js (index.js:56)
    at __webpack_require__ (bootstrap 64dbecc80b6a9be06bf0:678)
    at fn (bootstrap 64dbecc80b6a9be06bf0:88)
    at Object.0 (registerServiceWorker.js:117)
    at __webpack_require__ (bootstrap 64dbecc80b6a9be06bf0:678)
    at ./node_modules/@firebase/app/dist/esm/index.js.Object.defineProperty.value (bootstrap 64dbecc80b6a9be06bf0:724)
    at bootstrap 64dbecc80b6a9be06bf0:724
setListeners @ firestore.js:130
(anonymous) @ actions.js:76
componentWillMount @ firestoreConnect.js:73
callComponentWillMount @ react-dom.development.js:6370
mountClassInstance @ react-dom.development.js:6435
updateClassComponent @ react-dom.development.js:7840
beginWork @ react-dom.development.js:8225
performUnitOfWork @ react-dom.development.js:10224
workLoop @ react-dom.development.js:10288
callCallback @ react-dom.development.js:542
invokeGuardedCallbackDev @ react-dom.development.js:581
invokeGuardedCallback @ react-dom.development.js:438
renderRoot @ react-dom.development.js:10366
performWorkOnRoot @ react-dom.development.js:11014
performWork @ react-dom.development.js:10967
requestWork @ react-dom.development.js:10878
scheduleWorkImpl @ react-dom.development.js:10732
scheduleWork @ react-dom.development.js:10689
scheduleTopLevelUpdate @ react-dom.development.js:11193
updateContainer @ react-dom.development.js:11231
(anonymous) @ react-dom.development.js:15226
unbatchedUpdates @ react-dom.development.js:11102
renderSubtreeIntoContainer @ react-dom.development.js:15225
render @ react-dom.development.js:15290
./src/index.js @ index.js:56
__webpack_require__ @ bootstrap 64dbecc80b6a9be06bf0:678
fn @ bootstrap 64dbecc80b6a9be06bf0:88
0 @ registerServiceWorker.js:117
__webpack_require__ @ bootstrap 64dbecc80b6a9be06bf0:678
./node_modules/@firebase/app/dist/esm/index.js.Object.defineProperty.value @ bootstrap 64dbecc80b6a9be06bf0:724
(anonymous) @ bootstrap 64dbecc80b6a9be06bf0:724

index.js:2178 The above error occurred in the <FirestoreConnect(Connect(App))> component:
    in FirestoreConnect(Connect(App)) (at index.js:52)
    in Provider (at index.js:51)
    in AppContainer (at index.js:56)

bug(orderedReducer): subcollections not updating state.ordered

Do you want to request a feature or report a bug?

Bug

What is the current behavior?

I'm using the following listener configuration for syncing a subcollection:

export default compose(
  firestoreConnect(props => [
    {
      collection: 'artists',
      doc: props.artistId,
      subcollections: [
        {
          collection: 'flights',
          orderBy: ['departureMoment'],
        },
      ],
      storeAs: 'flights',
    },
  ]),
  connect(({ firestore }) => {
    return {
      flights: firestore.ordered.flights || [],
    };
  }),
)(FlightPage);

The resulting firestore object looks like this:

{
  data: {
    flights: {
      fnEPGX7kGPicCInJkDO3: {...document 1...},
      llOt1wbuTGNMpTHCaurr: {...document 2...}
    }
  },
  ordered: {
    flights: []
  }
}

The ordered result is an empty array, but the data result contains the correct documents.

When I inspect the corresponding @@reduxFirestore/LISTENER_RESPONSE action with redux-logger, it looks like this:

{
  meta: {...},
  payload: {
    data: {
      fnEPGX7kGPicCInJkDO3: {...document 1...},
      llOt1wbuTGNMpTHCaurr: {...document 2...}
    }
    ordered: [
      {...document 1...},
      {...document 2...}
    ]
  }
}

The action payload looks correct. However, the ordered data is not getting mapped correctly.

What is the expected behavior?

I would expect the ordered result to contain the same documents as the data object, but then in an ordered array. Now, the ordered array is empty.

Which versions of dependencies, and which browser are affected by this issue? Did this work in previous versions or setups?
redux: 3.7.2
redux-firestore: 0.2.5
react-redux: 5.0.6
react-redux-firebase: 2.0.0-rc.2

`firestore.update` throws an error

I think this is a bug or a documentation error. Current running [email protected].

The firestore.update example in the README.md is throwing the following error for me:

TypeError: Cannot read property 'apply' of undefined
wrapInDispatch
node_modules/redux-firestore/es/utils/actions.js:47
  44 |   meta: meta,
  45 |   payload: (0, _isObject3.default)(requestingType) ? requestingType.payload : { args: args }
  46 | });
> 47 | var methodPromise = args && args.length ? ref[method].apply(ref, _toConsumableArray(args)) : ref[method]();
  48 | return methodPromise.then(function (val) {
  49 |   var makePayload = function makePayload(_ref2) {
  50 |     var payload = _ref2.payload;

It is unclear if there is another method I should be using for updating records.

feat(reducers): support reference data type

hello

Do you want to request a feature or report a bug?
feature

What is the current behavior?
data type

db.collection("posts").doc("QyJJKtQhNA2QeHFVqfCR") = {
  content: String,
  author: Reference // 'users/jRjjlMyTBENjvln3pQpGwKgdvAa2'
}

query

{ collection: 'posts', doc: postId }

result

{ content: '', author: DocumentReference }

A DocumentReference refers to a document location in a Firestore database and can be used to write, read, or listen to the location. The document at the referenced location may or may not exist. A DocumentReference can also be used to create a CollectionReference to a subcollection.

image

What is the expected behavior?

{ content: '', author: { displayName: '', avatarUrl: '' } }

bug(dataReducer): setListener(s) clear's out the subcollection of a document

IT looks as though when a document updates through setListener(s) the data I get back does not include any subcollections I have previously pulled.

      loadData: ({ store, itemId }) => () =>
        store.firestore
          .get({
            collection: "items",
            doc: itemId,
            subcollections: [{ collection: "additions" }],
          })
          .then(
            store.firestore.setListener({
              collection: "items",
              doc: itemId,
              subcollections: [{ collection: "additions" }],
            }),
          ),

I have my redux connect listening to firestore.data.items[itemId].additions

I expected that when the listener updates the root item, it wouldn't clear out the additions subcollection. However when I get data back from the listener, the additions subcollection is missing.

Is this expected behavior, if so how should I work around it?

complete example : yarn start : unknown plugin "lodash"

Do you want to request a feature or report a bug?
BUG

What is the current behavior?
example complete fails to run/build

What is the expected behavior?
Run/build example complete

Which versions of dependencies, and which browser are affected by this issue? Did this work in previous versions or setups?
I have yarn 1.4.0, did not change any of the package.json, but got, when running yarn :

Please choose a version of "react-redux-firebase" from this list: (Use arrow k
eys)
❯ 2.1.1 
  2.1.0 
  2.0.7-alpha 
  2.0.6 
  2.0.5 
  2.0.4 
  2.0.3 

I chose the latest 2.1.1
Then

warning codecov > request > [email protected]: Use uuid module instead
[2/4] 🚚  Fetching packages...
[3/4] πŸ”—  Linking dependencies...
warning "firebase > @firebase/[email protected]" has unmet peer dependency "@firebase/[email protected]".
warning "firebase > @firebase/[email protected]" has unmet peer dependency "@firebase/[email protected]".
warning "firebase > @firebase/[email protected]" has unmet peer dependency "@firebase/[email protected]".
warning "firebase > @firebase/[email protected]" has unmet peer dependency "@firebase/[email protected]".
warning "firebase > @firebase/[email protected]" has unmet peer dependency "@firebase/[email protected]".
warning "firebase > @firebase/functions > @firebase/[email protected]" has unmet peer dependency "@firebase/[email protected]".
warning "firebase > @firebase/firestore > @firebase/[email protected]" has unmet peer dependency "@firebase/[email protected]".
warning "firebase > @firebase/database > @firebase/[email protected]" has unmet peer dependency "@firebase/[email protected]".
warning "firebase > @firebase/auth > @firebase/[email protected]" has unmet peer dependency "@firebase/[email protected]".
warning "firebase > @firebase/storage > @firebase/[email protected]" has unmet peer dependency "@firebase/[email protected]".

And then when running yarn start :
capture d ecran 2018-05-11 a 19 20 47

Steps to reproduce and if possible a minimal demo of the problem via codesandbox or similar.

Querying nonexistent data adds an entry in firestore.ordered but not firestore.data

Do you want to request a feature or report a bug?

  • Bug

Not sure if this is intentional or not though, but inconsistent to rely on I find. Happy to make a PR to correct them β€”Β just needs to double check to see if this is a bug or not.

What is the current behavior?

Consider this action:

{
  type: '@@reduxFirestore/LISTENER_RESPONSE',
  meta: {
    collection: 'group',
    doc: 'uJH3akkXRkje3ruPZ7au',
    subcollections: [
      {
        collection: 'userAccess',
        doc: 'nonexistent'
      }
    ],
    storeAs: 'group/uJH3akkXRkje3ruPZ7au/userAccess/'
  },
  payload: {
    data: null,
    ordered: []
  }
}

Will result in the store being updated as:

{ 
  firestore: {
    ordered: {
      group/uJH3akkXRkje3ruPZ7au/userAccess/: []
    }
  }
}

Which is supposedly inconsistent with how the store's firestore.data gets updated, and the action payload being incorrect based on the docs of the orderedFromSnap() return type, which is Array|null.

What is the expected behavior?

The action.payload should be:

payload: {
  data: null,
  ordered: null
}

And the store's firestore.data should have an entry of group/uJH3akkXRkje3ruPZ7au/userAccess/ as null instead of undefined and that part of the store not being updated. This way the isLoaded check from react-redux-firebase can rely on the behavior of firestore.data on that part.

Which versions of dependencies, and which browser are affected by this issue? Did this work in previous versions or setups?

Running redux-firestore 0.2.5.

Steps to reproduce and if possible a minimal demo of the problem via codesandbox or similar.

Query an endpoint that will return null as the payload data. In my case it was a nonexistent document in a collection.

readme issues

I couldn't setup the library to start experimenting, because I think the README is incomplete.

  1. redux-firestore isn't even imported.
  2. There's a mention of firestoreReducer, but redux-firestore does not have an export named firestoreReducer, it has one named firebaseStateReducer. This creates further confusion, because the reducer export of the original react-redux-firestore is also named firebaseStateReducer

Feature Request: StoreAs

The 'storeAs' property does not appear to be implement in redux-firestore. It would be very helpful if was supported.

Querying subcollections always warns "Listener does not exist"

In one of our components we are querying a subcollection like this:

    firestoreConnect((props) => {
      const { userId } = props;

      if (props.userId) {
        return [
          {
            collection: 'stripeCustomers',
            doc: userId,
            subcollections: [{ collection: 'sources' }],
            storeAs: 'stripeSources',
          },
          {
            collection: 'stripeCustomers',
            doc: userId,
            subcollections: [{ collection: 'charges' }],
            storeAs: 'stripeCharges',
          },
        ];
      }
      return [];
    })

When starting the app, this always shows 2 warnings:

Listener does not exist for stripeCustomers/someUserId/sources
Listener does not exist for stripeCustomers/someUserId/charges

I looked at the code that generates these 2 errors, but was unable to understand whether this is a correct or incorrect warning, as it seems like the listener is not registered initially, and then the detachListener function is run for some reason?

console.warn(`Listener does not exist for ${name}`); // eslint-disable-line no-console

Not getting data from firestore

Hi I am trying to use this component in combination with react-redux-firebase, but I did not get any data from my firestore. I am trying different things for one day now, but no luck yet. The authentication is working fine.

I also don't get how collections and documents are handled. In my case -Ktg8j9RjgIvUmCC1iGe references a document. Does it know which is a document or a collection automatically?

I try to use connect like this:

export default connect<StateFromProps, {}, void>(( state: any ) => (
    {
        auth: state.firebase.auth,
        apartmentList: getVal(state.firestore, 'data/users/pLiT8PvTBgbERBwUe8xPByJBtVn1/apartmentList/-Ktg8j9RjgIvUmCC1iGe', 'init')

    }))(
    firestoreConnect(['/users/pLiT8PvTBgbERBwUe8xPByJBtVn1/apartmentList/-Ktg8j9RjgIvUmCC1iGe'])(
        withStyles(styles)(App)
    )
);

My setup looks like this:

import App from './App';
import registerServiceWorker from './registerServiceWorker';
import './index.css';
import theme from './theme/theme';

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { createStore, combineReducers } from 'redux';
import { firebaseStateReducer, firestoreReducer, reactReduxFirebase } from 'react-redux-firebase';
import 'firebase/firestore';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { Provider } from 'react-redux';
import * as firebaseApp from 'firebase/app';
import * as firebase from 'firebase';
import { reduxFirestore } from 'redux-firestore';

const firebaseConfig = {
    ... here is my config...
};

const rrfConfig = {
    userProfile: 'users',
    useFirestoreForProfile: true
};

firebaseApp.initializeApp(firebaseConfig);
firebaseApp.firestore();


const createStoreWithFirebase = reduxFirestore(firebaseApp, {})(
    reactReduxFirebase(firebase, rrfConfig)(createStore)
);

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

// Create store with reducers and initial state
const store = createStoreWithFirebase(rootReducer, {});

ReactDOM.render(
    <MuiThemeProvider theme={theme}>
        <Provider store={store}>
            <App/>
        </Provider>
    </MuiThemeProvider>,
    document.getElementById('root') as HTMLElement
);
registerServiceWorker();

bug (data): Document_modified from nested collection incorrectly merged in the data reducer

Do you want to request a feature or report a bug?
bug

What is the current behavior?
When a document gets updated and the DOCUMENT_MODIFIED is triggered it isn't merging the data correctly in the data reducer.

What is the expected behavior?
We have a listener on companies/{companyid}/users
When a user object gets changed a DOCUMENT_MODIFIED action gets dispatched, but instead of merging the new user inside of companies/{companyid}/users/{userid} -> the document is being inserted in /companies/{userId}

Which versions of dependencies, and which browser are affected by this issue? Did this work in previous versions or setups?
I'm using 0.4.2, but I see that the document_modified hasn't changed in 0.4.3

feat(core): method to expose instance for use in redux-saga and redux-thunk

I experience issues when fetching data with the get operator.
Works seamlessly when adding data to Firestore though.

Tested on master and v0.1.0-alpha.2 – using react-redux-firebase as the base, but since they have made redux-firestore optional it's a combination of the two.

Uncaught (in promise) TypeError: Cannot read property 'collection' of undefined

Any idea why?

"QuerySnapshot.docChanges has been changed from a property into a method" error.

Do you want to request a feature or report a bug?
Bug

What is the current behavior?
Collection doesn't load, get an error in console.

What is the expected behavior?
Collection in my Firestore should be loaded.

Which versions of dependencies, and which browser are affected by this issue? Did this work in previous versions or setups?
I'm using latest (0.5.2) version in latest Chrome.

Steps to reproduce and if possible a minimal demo of the problem via codesandbox or similar.

Very simple so far:

import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux'
import { compose } from 'recompose';
import { firestoreConnect } from 'react-redux-firebase'

function Main(props) {
  console.log(props);
  return (
    <div>Cards go here</div>
  )
}

Main.propTypes = {};

const enhance = compose(
  firestoreConnect(['cards']),
  connect((state) => ({
    cards: state.firestore.ordered.cards,
  }))
);

export default enhance(Main);

Cards is undefined and I get the following error in console:

Uncaught Error: QuerySnapshot.docChanges has been changed from a property into a method, so usages like "querySnapshot.docChanges" should become "querySnapshot.docChanges()"
    at new FirestoreError (index.cjs.js:346)
    at throwDocChangesMethodError (index.cjs.js:17164)
    at Function.get (index.cjs.js:17176)
    at Object.next (firestore.js:164)
    at next (index.cjs.js:16990)
    at index.cjs.js:15021

I have a top-level cards collection in my Firestore which has a few items in it, shouldn't be returning undefined. I'm guessing it's due to this error.

(question) Recursive subscription

What would be the best approach to subscribe to any change in the tree?

My firestore document layout

rootcollection
    doc1
       subcollection11
          subdoc1
          subdoc2
    doc2
       subcollection21

For example

  • root level doc addition/removal/change
  • subcollection addition/removal/change
  • subdoc1 addition/removal/change

I tried

import { getFirestore } from 'redux-firestore';
getFirestore().get('/rootcollection') or getFirestore().setListeners('/rootcollection')

But it did not give me any data on subcollection level.
Do i need to handle the subscription myself on client level? Or is there a better way?

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.