簡體   English   中英

錯誤:“輸入”過濾器需要非空數組

[英]Error: A non-empty array is required for 'in' filters

我想創建將運行 react-firebase-hooks 庫鈎子的自定義鈎子: useCollection 我在我的項目中使用 redux 工具包作為 state 經理,redux 為我的自定義掛鈎提供游戲數據。 我需要從商店獲取連接的玩家 ID: game.players: string[] 但問題是有時游戲仍然不會被提取,有時它可能是null並且新創建的游戲沒有任何連接的玩家。

我創建了自己的實現:

export const useGamePlayers = () => {
    const {game} = useTypedSelector(state => state.game);

    return useCollection(
        query(collection(db, 'players'), where(documentId(), 'in', game?.players))
    )
};

但是當我使用這個鈎子時,我看到了這個錯誤: Uncaught FirebaseError: Invalid Query。 “in”過濾器需要一個非空數組。 這是因為新游戲有 0 個連接的玩家。

所以問題是 -如何根據數組長度有條件地執行 hook?

解決方案非常簡單。 我沒有得到的是,當沒有玩家連接或玩家數組不存在時,我可以傳遞 null 而不是查詢集合。

export const useGamePlayers = () => {
    const {game} = useTypedSelector(state => state.game);

    return useCollection(
        game?.players.length
            ? query(collection(db, 'players'), where(documentId(), 'in', game.players)) 
            : null
    )
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM