react-firebase-hooks icon indicating copy to clipboard operation
react-firebase-hooks copied to clipboard

Unable to use postConverter example for transforming data without TypeScript

Open zaneshaw opened this issue 3 years ago • 3 comments

I'm attempting to use the "postConverter" example provided in the the "Transforming data" section of the docs. I'm using Firebase v9 without TypeScript and I'm not sure how to implement the example. The only reason I want to use a the postConverter example is to easily get the id of a doc while still using the "useCollectionData" hook.

Sorry for making an issue, I just need some assistance on this. Thanks!

zaneshaw avatar Apr 18 '22 14:04 zaneshaw

It doesn't seem to work. cause a dead loop or something, run out of quote quickly.

railty avatar May 02 '22 17:05 railty

@squidee100 @railty I was able to use the converter but not exactly the way it is in docs. You need to return a new class object from fromFirestore as follow:

class YourClass {
  customField
  ref
  id

  constructor(customField, ref, id) {
    this.customField = customField
    this.ref = ref
    this.id = id
  }
}

const converter = {
   toFirestore: (entity) => ({ customField: entity.customField }),
  fromFirestore: (snapshot) => {
    const data = snapshot.data()
    return new YourClass(data.customField, snapshot.ref, snapshot.id)
  },
}

I hope it works for you guys.

csuriel avatar May 23 '22 01:05 csuriel

Be careful about referential equality when using converters @railty.

I ran into a similar issue with an endless loop of queries. It's because this package is checking if query is referentially equal when doing a query. The idea is that if you change query, then it should do another query with your new input.

When creating a converter inside a React component, you will get a new object created on each render, thus when you pass that into the firestore query, the query will constantly change on every render, thus triggering this package to run another query, and you end up in an endless render loop.

The solution is to always define converters outside of the React component (so it only gets defined once), or put it inside a memo, so it's always referentially equal.

dangreaves avatar Jun 29 '22 05:06 dangreaves

Closing as this appears to have been answered. Please re-open if it is still an issue

chrisbianca avatar Nov 04 '22 16:11 chrisbianca