首页 > 解决方案 > 反应延迟后如何调用firebase钩子?

问题描述

我正在添加新用户。在后端,我需要大约 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)

}

标签: reactjsfirebasefirebase-realtime-databasereact-hooks

解决方案


我不认为我明白,但你尝试过 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]);

推荐阅读