useState()
in a Nuxt3 has a power of sending data to client after fetching it on server side (except rendered HTML file, it sends JSON file with data saved using useState()
).
Like I mentioned in the title, I want to fill indexedDB on client side with data, so I don’t need to fetch data again. I enableIndexedDbPersistence(getFirestore())
in a plugin on client side.
Example of component where I want to save existing data to indexedDB:
<template>
<div>
<h1>Data</h1>
{{ data }}
</div>
</template>
<script setup lang="ts">
import { getDocs, collection, getFirestore } from '@firebase/firestore/lite'
const data = useState('test2')
// data.value === unknown on server side, but on client it has data
if(!data.value) {
const result = await getDocs(collection(getFirestore(), 'test2'))
if(!result.empty) data.value = result.docs.map(docSnap => { return { ...docSnap.data(), id: docSnap.id } })
} else {
// Fill indexedDB maintained by JS Firebase client SDK
// `enableIndexedDbPersistence(getFirestore())`
// with data so SDK wont need to fetch data again
// when i use `onSnapshot()` with same query
}
</script>
For people not know how Nuxt3 works:
Code in <script setup>
tag run server side and template is rendered. useState()
is a state management with a powerful feature. It sends a JSON file with data to a client so when the component is opened on the client it already has fetched data
done one server side. That why if(!data.value)
statement to prevent from double fetch.
2
Answers
If I store and persist data using Firebase client SDK in a browser using
enableIndexedDbPersistence(getFirestore())
, Nuxt3 still will make requests to a server every time a user open a new tab to my web app. It's happening because files I'm getting from the server have headers withCache-Control: max-age=0
.Best way will be to just make PWA (Progressive Web Application) where I can manipulate files headers and change
Cache-Control: max-age=X
, so the app will work as SPA (Single Page Application) every time user visit again my web app, andenableIndexedDbPersistence(getFirestore())
from Firebase SDK will do the work.And there is no point to "Prevent second query by Firebase on client side" if PWA will prevent Nuxt3 from SSR every time user opens tab. All I can benefit from it is to save one query when user visit my web page first time in a brawser.
IMHO I don’t think it is a good idea to try "manipulating" data stored and managed by the JS SDK in the local persistent storage. The cache management is a quite complex process and is not a matter of just pushing data to the browser local storage.
If I correctly understand your requirement, it is already covered by the local cache mechanism: If a document is in the local cache, as long as the document in the database is not changed any subsequent read is done from the cache. If a document in the database is changed, it is fetched from the Firestore back-end and you are charged with a document read.