0

I have a product page with all my product and every time someone presses F5 it get executed. I want to save all de product but when a product is added it can get update once to reduce all the api calls.

//JS file My cookie try: it works i only get a api call every 0.5 days but if a update happens in my product i only get is later

//if cookie === undifined
const firestore = firebase.firestore()
firestore.doc("products/phones").onSnapshot(function (doc) {
    if (doc && doc.exists) {
        const products = doc.data().produc
        //Save doc.data().produc in cookie 0.5 day expirery
    }
})

I want to save my Firestore request client side and only make a Firestore request when needed to update the product list.

Lars Rijnen
  • 313
  • 1
  • 3
  • 13

1 Answers1

2

Your second approach has no chance of working. The firebase.json file is using by Firebase Hosting and completely unrelated to Cloud Firestore.

Your first approach could work, although you didn't include the code that actually determines when you attach the onSnapshot listener. But as you discovered, attaching the listener at most twice a day means that you only get updates at most twice a day, and that you may be serving stale data in the meantime.

It sounds like you'll have to choose between serving fresh data, and reducing server calls. This is a fairly common trade-off.

There are a few other ways to reduce the number of document reads needed to server the latest data though:

  1. Include a timestamp when the data was updated in each document, and then use a query to only request new data. You'll keep the timestamp of when you last requested/got data in local storage, and use that in the query each time.
  2. Aggregate the data for recent updates into one or a few documents, so that you have to read fewer documents.
Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807