【问题标题】:Firebase: "TypeError: currentUser.updateProfile is not a function" after merging firebase user with another objectFirebase:将firebase用户与另一个对象合并后“TypeError:currentUser.updateProfile不是函数”
【发布时间】:2021-05-31 08:25:49
【问题描述】:

我正在尝试使用 updateProfile() 更新用户的个人资料

当我完全按照link above 中的示例调用该函数时,它会抛出TypeError: currentUser.updateProfile is not a function。我尝试console.log() 用户,但奇怪的是它没有显示updateProfile() 功能。

我正在使用从auth.onAuthStateChanged() 检索到的用户。然后我使用 Firebase firestore 来存储其他用户信息。我将该用户对象与从 firestore 检索到的数据合并:

const mergedUser = Object.assign({}, user, doc.data())

我将mergedUser 传递给一个useState() currentUser,该currentUser 将传递给我的上下文提供程序值。

其他一切都有效,但应该在 userobject 上的函数在 Object.assign() 之后不存在。如何合并用户对象,以便我可以访问所有用户数据和 firebase 用户功能,例如updateProfile()

提前谢谢你!

package.json:

{
  "name": "planom",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "firebase": "^8.2.7",
    "next": "10.0.6",
    "react": "17.0.1",
    "react-dom": "17.0.1",
    "sass": "^1.32.7"
  },
  "devDependencies": {}
}

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore firebase-authentication next.js


    【解决方案1】:

    Object.assign 复制所有可枚举的属性 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)。但是,这不包括不可枚举的属性(如原型方法)。

    我能想到几个不同的解决方案:

    使用firebase.auth().currentUser

    firebase.auth().currentUser 已经在全局范围内可用,因此您可以通过这种方式访问​​方法

    重组你的状态

    不要尝试组合userdoc.data(),而是让它们成为新对象的不同属性。例如:

    {
      user: user,
      userData: doc.data()
    }
    

    (这里的缺点是您仍在尝试使用状态中的方法来存储复杂对象 - 例如,如果依赖于重新水化的状态,则不理想)

    使用 Object.create?也许?

    就个人而言,如果我是你,我不会乱用这个系统,因为如果底层 API 发生变化,前两个会更简单、更可靠,但你可以尝试使用 Object.create 然后 Object.assign 来创建一个确实具有可用原始方法的对象。看到这个答案:Using Object.assign and Object.create for inheritance

    【讨论】:

    • 啊,好吧。我一定会研究这些,看看什么效果最好。谢谢!
    【解决方案2】:

    确保您的 js 文件链接位于所有其他 firebase 脚本导入的下方。 如果您以错误的顺序链接它们,您的错误很常见,如果您在标题中链接到您的脚本,也不要忘记推迟脚本标签。

    <script src="myJS.js" defer></script>
    

    延迟确保在 HTML 之后读取 js 文档,如果您复制了 firebase js-imports,它们也会被延迟。

    【讨论】:

    • 我正在使用 next.js,所以我没有设置任何类似的东西。我不认为这是你(通常)使用 next.js 的方式
    • 谢谢你:)
    猜你喜欢
    • 2019-09-14
    • 2017-12-24
    • 2020-07-22
    • 2019-03-12
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多