await setDoc无法在Next.js中使用Firestore:服务器/客户端代码问题?

k4aesqcs  于 2023-05-28  发布在  其他
关注(0)|答案(1)|浏览(91)

在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,它工作得很好,所以一定有某种服务器/客户端问题。
我期待着消防队的更新。

db2dz4w8

db2dz4w81#

您的firebase配置不完整。必须包含databaseURL才能与firestore通信。在将环境变量暴露给浏览器时,您应该在`next.js中的PUBLIC之前添加NEXT前缀。
下面是示例代码片段:

// 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 };

参考:https://firebase.google.com/docs/web/setup/#add-sdks-initialize

相关问题