【问题标题】:Firebase Query for uid of current user gives error that current user is null当前用户的 uid 的 Firebase 查询给出了当前用户为空的错误
【发布时间】:2021-08-24 23:37:21
【问题描述】:

对于我当前的 react 项目,我想使用 firebase 存储和身份验证。用户可以使用形状创建基本对象

{
    createdAt: timestamp
    creator: uid of the user
    email: String
    name: String
}

现在我想向用户展示他创建的所有对象。所以我用了

const auth = firebase.auth()
const firestore = firebase.firestore();
const clientsRef = firestore.collection('clients');
const query = clientsRef.orderBy('createdAt').where('creator','==','auth.currentUser?.uid';

const Clients = () => {
const [clients] = useCollectionData(query);

return (
        <div className="client-list">
            <h1>Your Clients</h1>
            <div className="client-listing">
                {clients && clients.map(client => {
                    return <List>
                        <ListItem button>
                            <ListItemText primary={client.name} />
                        </ListItem>
                    </List>
                })}
            </div>
        </div>
)}

由于用户在显示此组件之前已登录,我认为应该有一个当前用户。但是 react 一直警告我当前用户为空,当我想启动代码时,它会向我显示错误:

FirebaseError:使用无效数据调用函数 Query.where()。不支持的字段值:未定义

我试图更新auth.onAuthStateChanged 上的查询,但是我遇到了麻烦,因为它无法在onAuthStateChanged 内运行useCollectionData,因为它给了我反应钩子不能出现的错误在回调中调用。

那么我怎么能只显示用户创建的数据,因为显示所有数据当然不是一个选项?

【问题讨论】:

  • 这行会报错,肯定不行:clientsRef.orderBy('createdAt').where('creator','==','auth.currentUser.uid';你确定这是你用的吗?如果是这样,您会收到什么错误消息?
  • 对不起,我使用了clientsRef.orderBy('createdAt).where('creator','==','auth.currentUser?.uid');` 然后的错误是FirebaseError: Function Query.where() called with invalid data. Unsupported field value: undefined

标签: reactjs firebase google-cloud-firestore firebase-authentication


【解决方案1】:

解决方法是为用户添加一个钩子,并检查是否设置了用户。然后必须更新查询。

const auth = firebase.auth()
const firestore = firebase.firestore();
const clientsRef = firestore.collection('clients');
let query = clientsRef.orderBy('createdAt');

const Clients = () => {
    const [detailedClient, setDetailedClient] = useState({});
    const [open, setOpen] = useState(false);
    const [clients] = useCollectionData(query);
    const [user]  = useAuthState(auth);    
    if(user){
            query = clientsRef.where('creator','==',user.uid);
    }

这会在authState 由于useAuthState(auth) 挂钩而更改后立即更新查询。然后使用.where() 更新查询。

【讨论】:

    猜你喜欢
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    • 2018-07-01
    • 2016-09-27
    • 2022-11-11
    • 2016-12-11
    • 2021-04-12
    相关资源
    最近更新 更多