Home > Back-end >  Error: A non-empty array is required for 'in' filters
Error: A non-empty array is required for 'in' filters

Time:01-26

I want to create custom hook that will run react-firebase-hooks library hook: useCollection. I use redux toolkit in my project as a state manager, and redux provides my custom hook with the game data. I need to grab connected players IDs from store: game.players: string[]. But the thing is that sometimes game won't be fetched still, sometimes it cab be null and new created game does not have any connected players.

I've created my own implementation:

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

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

But when i use this hook I see this error: Uncaught FirebaseError: Invalid Query. A non-empty array is required for 'in' filters. This is happening beacause new game has 0 connected players.

So the question is - How can I conditionally execute hook depending on the array length?

CodePudding user response:

The solution was quite simple. The thing i didn't get is that I can pass null instead of querying collection when no players are connected or players array doesn't exists.

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

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