IjzerenHein / firestorter

Use Google Firestore in React with zero effort, using MobX 🤘
http://firestorter.com
MIT License
378 stars 50 forks source link

Trigger listener on get #98

Closed RWOverdijk closed 4 years ago

RWOverdijk commented 4 years ago

Where products is a Collection Is there a way to prevent having to do something like this:

products.docs.map(x => x)[0]?.data

And instead just allow this:

products.docs[0]?.data

Unless I map, the data never gets retrieved. It seems to me that this could be done because it's also possible to Proxy arrays, I just think I don't understand this library very well. 😄

IjzerenHein commented 4 years ago

Hmm, good one. I guess you would need have a write some kind of helper function for that. Perhaps something like this?

function getFirstDoc(col: Collection) {
  return products.length ? products.slice(0)[0] : undefined;
}

As for the docs[0] construct, I would have expected that to work tbh. Not sure why that doesn't create a MobX reaction, might be a problem with the MobX proxy indeed, or TypeScript might convert it to an unexpected JS construct.

RWOverdijk commented 4 years ago

@IjzerenHein If you mean typescript on my end, I am sad to say I'm not using typescript (but only because expo init doesn't do what I need right now).

As to the helper, that'd be fine. I can do that.

So what if I need one document's id to find documents from another collection? Practical example:

I have venues. Venues need to be looked up by slug:

{
    query: (ref) => ref.where('slug', '==', slug).limit(1)
  }

Then I need to use the document ID to find something else in a constructor, like orders:

order/${user.uid}/venue/${venueID}/product

But I do want to maintain the live updates (otherwise I'd simply use .fetch and turn off auto updates).

Right now I'm doing this:

const venue = await findBySlug(this.props.route.params.slug)
const orders = await findOrders(venue.id)

Which doesn't feel ideal.

Update:

I am now doing this:

  async findBySlug (slug) {
    const snapshot = await VenueRepository.collection({
      mode: 'off',
      query: (ref) => ref.where('slug', '==', slug).limit(1)
    }).fetch()

    const venueDocument = new Document(`venue/${snapshot.docs[0].id}`, { mode: 'on' })

    await venueDocument.ready()

    return venueDocument
  }

Would you say this is a good way of doing it? In any case feel free to close this, at this point it's me asking too many questions.