简体   繁体   中英

Nextjs App how to handle local data storage after querying with Firestore?

I'm developing a react e-commerce app with Firestore database. When the app loads it fetches first 50 products (each one is a Firestore doc), and renders the product card with the data. My question is where to store this data for easy access in case of page refresh, navigation to say to order page and come back to the products page, close the tab and open again etc.

I'm asking this because when I monitor my Firestore usage for following;

  1. I open products page and load 50 products, go to second page load another 50 etc.
  2. Do filtering get another 50 products, remove filters, get the first 50 products again.
  3. Go to orders page come back get 50 products.

All in all one session can easily reach thousands of doc reads, lots of data use and longer load times. So I think I`m missing a point here. There should be a way to store all these data without making the app slower and data usage more expensive. What would be a good approach here to save the data in session and full refresh, close the tab and come back etc. ?

PS I'm using Next.js and Firestore, data fetching is done on the client side via Firestore web library.

As soon as you get the data from firebase simply store it over local storage as follows,

considering you get the data of component load like in a useEffect and store it in a state name as product. Now my approach would be to look for any update in product variable through useEffect and simply update the local storage

const [product,setproduct] = useState([]); // containing array of product
useEffect(() => {
   if(product.length>0) localStorage.setItems('products',JSON.stringify(product));
  }, [product]);

That way you have it on localstorage and use it anywhere around the application. Also in other components while calling firestore to get product make sure to check local storage first. If there is already some data stored over local storage, dont go up for calling firestore to get data.

That will reduce you API calls and along side increase the performance of the application.

Voila. I hope it solves your purpose: :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM