“await setDoc 在 Next.js 中与 Firestore 不起作用:是服务器/客户端代码问题吗?”

huangapple go评论54阅读模式
英文:

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 &#39;next/font/google&#39;
import { initFirebase} from &quot;@/lib/firebase/initFirebase&quot;;
import WriteToCloudFirestore from &quot;@/componenets/cloudFirestore/Write&quot;;

const inter = Inter({ subsets: [&#39;latin&#39;] })

export default function Home() {

  initFirebase()

  return (...)

initFirebase.js

import {  initializeApp } from &quot;firebase/app&quot;;
import { getFirestore } from &quot;firebase/firestore&quot;;

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(&quot;Firebase has been initialized successfully&quot;);
    }
}

const app = initializeApp(clientCredentials);

const db = getFirestore(app);

export {initFirebase, db};

write.js

import { db } from &#39;@/lib/firebase/initFirebase&#39;
import {doc, setDoc} from &quot;firebase/firestore&quot;;


const WriteToCloudFirestore =  () =&gt; {
    const sendData = async () =&gt; {
        try {
            const userDoc = doc(db, &quot;myCollection&quot;, &quot;myDoc&quot;)
            alert(&quot;starting&quot;)
            await setDoc(userDoc, {
                string_data: &#39;John Doe&#39;,
                number_data: 2,
                boolean_data: true,
                map_data: {stringInMap: &#39;Hi&#39;, numberInMap: 7},
                array_data: [&#39;text&#39;, 4],
                null_data: null,
            })
            alert(&#39;Data was successfully sent to cloud firestore!&#39;)
        } catch (error) {
            console.log(error)
            alert(error)
        }
    }


    return (
        &lt;div style={{margin: &#39;5px 0&#39;}}&gt;
            &lt;button onClick={sendData} style={{width: &#39;100%&#39;}}&gt;Send Data To Cloud Firestore&lt;/button&gt;
        &lt;/div&gt;
    )
}

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 &quot;firebase/app&quot;;
import { getFirestore } from &quot;firebase/firestore&quot;;
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app&#39;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

huangapple
  • 本文由 发表于 2023年5月26日 09:43:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76337170.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定