【发布时间】:2021-06-16 01:31:55
【问题描述】:
我正在使用 fetch() 钩子in Nuxt with Firestore,当在服务器上调用它时,它总是返回一个空数组。如果从客户端调用,它会返回一个填充数组
created(){
this.$fetch() //called on client, logs populated array and json
},
async fetch(){
const products = await this.$fire.firestore.collection('products').get();
const ps = products.docs.map(doc=>doc.data());
console.log(ps); //logs an empty array on Nuxt SSR
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/38`)
const l = await res.json();
console.log(l); //always logs a value on client or SSR
}
我可以就这里发生的事情以及如何解决它提供一些指导吗?我觉得很奇怪,对jsonplaceholder 的调用总是返回数据,但对 firebase 的调用却没有。请参阅下面的console 的图像
当按下 CTRL + SHIFT + R 时:
当有热重载或客户端导航时:
products.vue
<template>
<v-container>
<h1>Products</h1>
<v-row>
<v-col v-for="product in products" :key="product.id" cols="3">
<v-card>
<v-card-title>
{{ product.category }}
</v-card-title>
</v-card>
</v-col>
</v-row>
</v-container>
</template>
<script>
export default {
data() {
return {
products: '',
}
},
async fetch() {
const products = await this.$fire.firestore.collection('products').get()
this.products = products.docs.map((doc) => {
return { ...doc.data(), id: doc.id, ref: doc.ref }
})
const res = await fetch(`https://jsonplaceholder.typicode.com/posts/38`)
const l = await res.json()
},
// fetchOnServer: false
}
</script>
【问题讨论】:
-
你试过使用 asyncData 吗?
-
@Dharmaraj
asyncData正在阻止渲染,而不是实际调用。两者都在服务器+客户端上运行。此外,这两个 API 在这里都称为客户端。测试服务器端将是:拥有 SSR 并禁用 JS 以查看发送到浏览器的 HTML。
标签: javascript firebase google-cloud-firestore nuxt.js hook