英文:
await setDoc not working in Next.js with Firestore: Server/Client code issue?
问题
Here's the translated content:
在Write.js中,await setDoc后什么都不会发生,我是否漏掉了什么?
我正在使用Next.js 12。我认为我的配置都没有问题,我认为在客户端和服务器端代码中使用await可能导致问题。
index.js
import { Inter } from 'next/font/google'
import { initFirebase} from "@/lib/firebase/initFirebase";
import WriteToCloudFirestore from "@/components/cloudFirestore/Write";
const inter = Inter({ subsets: ['latin'] })
export default function Home() {
initFirebase()
return (...)
initFirebase.js
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const clientCredentials = {
apiKey: process.env.PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.PUBLIC_FIREBASE_PROJECT_ID,
}
function initFirebase() {
if (typeof window !== undefined) {
initializeApp(clientCredentials);
console.log("Firebase已成功初始化");
}
}
const app = initializeApp(clientCredentials);
const db = getFirestore(app);
export { initFirebase, db };
write.js
import { db } from '@/lib/firebase/initFirebase'
import { doc, setDoc } from "firebase/firestore";
const WriteToCloudFirestore = () => {
const sendData = async () => {
try {
const userDoc = doc(db, "myCollection", "myDoc")
alert("开始")
await setDoc(userDoc, {
string_data: 'John Doe',
number_data: 2,
boolean_data: true,
map_data: { stringInMap: 'Hi', numberInMap: 7 },
array_data: ['text', 4],
null_data: null,
})
alert('数据已成功发送到Cloud Firestore!')
} catch (error) {
console.log(error)
alert(error)
}
}
return (
<div style={{ margin: '5px 0' }}>
<button onClick={sendData} style={{ width: '100%' }}>将数据发送到Cloud Firestore</button>
</div>
)
}
export default WriteToCloudFirestore
我尝试在initFirebase函数中运行setDoc,它可以正常工作,所以可能存在某种服务器/客户端问题。
我期望Firestore会被更新。
英文:
Nothing happens following await setDoc in Write.js am I missing something
I am using Nextjs 12. My configuration is all good, I think there is a problem with await in client vs server code which is causing issues
index.js
import { Inter } from 'next/font/google'
import { initFirebase} from "@/lib/firebase/initFirebase";
import WriteToCloudFirestore from "@/componenets/cloudFirestore/Write";
const inter = Inter({ subsets: ['latin'] })
export default function Home() {
initFirebase()
return (...)
initFirebase.js
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const clientCredentials = {
apiKey: process.env.PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.PUBLIC_FIREBASE_PROJECT_ID,
}
function initFirebase() {
if (typeof window !== undefined) {
initializeApp(clientCredentials);
console.log("Firebase has been initialized successfully");
}
}
const app = initializeApp(clientCredentials);
const db = getFirestore(app);
export {initFirebase, db};
write.js
import { db } from '@/lib/firebase/initFirebase'
import {doc, setDoc} from "firebase/firestore";
const WriteToCloudFirestore = () => {
const sendData = async () => {
try {
const userDoc = doc(db, "myCollection", "myDoc")
alert("starting")
await setDoc(userDoc, {
string_data: 'John Doe',
number_data: 2,
boolean_data: true,
map_data: {stringInMap: 'Hi', numberInMap: 7},
array_data: ['text', 4],
null_data: null,
})
alert('Data was successfully sent to cloud firestore!')
} catch (error) {
console.log(error)
alert(error)
}
}
return (
<div style={{margin: '5px 0'}}>
<button onClick={sendData} style={{width: '100%'}}>Send Data To Cloud Firestore</button>
</div>
)
}
export default WriteToCloudFirestore
I tried running the setDoc in the initFirebase function and it worked so, there must be some sort of server/client issue.
I am expecting the firestore to be updated.
答案1
得分: 1
你的 firebase
配置不完整。你必须包括 databaseURL
以与 Firestore 进行通信。同时,在将环境变量暴露给浏览器时,你应该在 next.js
中的 PUBLIC 之前添加 NEXT 前缀。
以下是示例代码片段:
// 从你需要的 SDK 中导入所需的函数
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
// TODO: 添加要使用的 Firebase 产品的 SDK
// https://firebase.google.com/docs/web/setup#available-libraries
// 你的 Web 应用的 Firebase 配置
// 对于 Firebase JS SDK v7.20.0 及更高版本,measurementId 是可选的
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID
};
// 初始化 Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
export { db };
参考链接: https://firebase.google.com/docs/web/setup/#add-sdks-initialize
英文:
You have incomplete firebase
configuration. You must include databaseURL
to communicate with firestore. And while exposing environment Variables to the Browser, you should prefix NEXT before PUBLIC in `next.js.
Here is the sample code snippet:
// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
databaseURL: process.env.NEXT_PUBLIC_FIREBASE_DATABASE_URL,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET,
messagingSenderId:process.env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
export { db };
Reference: https://firebase.google.com/docs/web/setup/#add-sdks-initialize
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论