在Write.js中await setDoc之后没有发生任何事情,我正在使用Nextjs 12。我的配置都很好,我认为客户端与服务器代码中的await有问题,这导致了问题
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
我试着在initFirebase函数中运行setDoc,它工作得很好,所以一定有某种服务器/客户端问题。
我期待着消防队的更新。
1条答案
按热度按时间db2dz4w81#
您的
firebase
配置不完整。必须包含databaseURL
才能与firestore通信。在将环境变量暴露给浏览器时,您应该在`next.js中的PUBLIC之前添加NEXT前缀。下面是示例代码片段:
参考:https://firebase.google.com/docs/web/setup/#add-sdks-initialize