Search code examples
javascriptreactjsfirebasegoogle-cloud-firestorewhere-clause

.where doesn't show results using react-firebase-hooks


Trying to get query results based on current user id. Which is stored in the documents collection under field "uid".

This is my code:

function Channels() {
  const currentUid = auth.currentUser.uid;
  const query = firestore
    .collection("multitwitch")
    .where("uid", "==", currentUid)
    .orderBy("createdAt");

  const [channels] = useCollectionData(query);

  return (
    <>
      <main>
        <div>
          {channels &&
            channels.map((chan) => (
              <ChannelStrip key={chan.id} channel={chan} />
            ))}
        </div>
      </main>
    </>
  );
}

function ChannelStrip(props) {
  const { twitchchannel } = props.channel;

  return (
    <>
      <iframe
        src={`https://player.twitch.tv/?channel=${twitchchannel}&parent=localhost&muted=true`}
        height="300"
        width="500"
        allowfullscreen
      ></iframe>
    </>
  );
}

When I add .where in the query this show no results.
But when I remove .orderBy it gives results.

Why is this?

Also tried to add indexing in firestore:

screenshot of created indexes

No Luck


Solution

  • Firestore queries work based on the existence of indexes that match exactly with the conditions and ordering of each query. By default Firestore automatically indexes all individual fields of your documents, which works for most simple queries.

    If you have both a where clause and an order by on different fields, you will need a composite index on those two fields and such indexes are not automatically created. You will instead have to create the index manually, which is likely what you forgot to do.

    There are two ways to do create the missing index:

    • If you catch and log errors in your code, the output will contain an error message about the missing index. This error message contains a link to the Firestore console with all information about the missing index pre-populated. So: open that link, click the button, wait until the index is built, and retry the query. This is documentation in creating a missing index through an error message
    • You can also manually create indexes, as shown in the documentation on creating indexes in the Firebase console