【问题标题】:How to call firebase hook after some delay in react?反应延迟后如何调用firebase钩子?
【发布时间】:2019-10-25 20:23:42
【问题描述】:

我正在添加新用户。在后端,我需要大约 2 秒才能访问我创建的新用户数据。错误的原因是访问控制。当我尝试使用 firebase 钩子获取用户时,它给了我一个错误:

错误:permission_denied at /users/M2uQPQRacJZxjCwxqVT0UlHcwy72:客户端无权访问所需数据。

刷新页面后,我可以访问新用户的数据,并显示在列表中。

我想知道有什么方法可以在几秒钟后调用 firebase hook,这样我就不会收到这个错误了吗?

Firebase 钩子:

 export const useUser = userId => {
   if (!userId) {
      return [null, false]
   }
   const ref = firebase.database().ref(`users/${userId}`)
   return useObjectVal(ref)
 }

用法:

import { useUser } from '../../hooks/firebase-hooks'

function TeamMemberListItem(props) {

  const userId = props.userId
  const [user, loading, error] = useUser(userId)

}

【问题讨论】:

  • 错误原因是什么?您是否尝试在创建用户之前显示它?
  • 错误原因是访问控制。在后端,我需要一些时间才能访问新的用户数据
  • 获得权限时是否有来自服务器的通知?
  • 不,但是当我刷新页面时它可以工作。后端开发人员告诉我在延迟 2 秒后调用该函数,然后它将起作用
  • 中继时间延迟不是一个好主意。 useObjectVal 做什么?

标签: reactjs firebase firebase-realtime-database react-hooks


【解决方案1】:

我不认为我确实理解了,但是您是否尝试过使用 useEffect ?也许如果你使用 useEffect 和 userId 作为第二个参数?

import React, { useEffect } from 'react';

useEffect(() => {
 // do something when the component is mounted or userId is updated

 setInterval(() => {
   // do something 2 seconds after the component is mounted or userId is updated
 }, 2000);
}, [userId]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 2019-06-07
    • 2021-03-19
    • 2020-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多