Search code examples
reactjsgoogle-cloud-firestore

TypeError: Cannot read properties of null (reading 'indexOf')


I am making a chat app using react and Firebase. I keep getting Type error either not being able to read undefined ('_delegate') or indexOf. There seems to be a problem with the useCollection hook.

const state = store.getState()
const serverId = useSelector((state) => state.server.serverId)

const inputRef = useRef('')
const chatRef = useRef(null)
const [user] = useAuthState(auth)
const serverRef = doc(db, 'servers', serverId)
const messagesRef = serverId ? collection(serverRef, 'messages') : null
const [messages] = useCollection(
    messagesRef ? orderBy(messagesRef?.timestamp, 'asc') : []
)
if (messages.error) {
    console.log(messages.error)
}

I map the messages via

messages?.docs?.map((doc) => {
    if (!doc.exists) return null
    const { message, name, photoURL, email, timestamp } = doc.data()
    return (
        <Message key={doc.id} id={doc.id} name={name} photoURL={photoURL} email={email} message={message} timestamp={timestamp} />
    )
})

How should I use my useCollection hook correctly?


Solution

  • You should initialize messagesRef and messagesQuery as null, construct the reference and query only if serverId is available, and pass the resulting query to useCollection.

    let messagesRef = null;
    let messagesQuery = null;
    
    if (serverId) {
      const serverRef = doc(db, 'servers', serverId);
      messagesRef = collection(serverRef, 'messages');
      messagesQuery = query(messagesRef, orderBy('timestamp', 'asc'));
    }
    
    const [messages, loading, error] = useCollection(messagesQuery);