I'm trying to query my firestore and I need the uid for the query. My issue is that when my page loads and I run the query, I get TypeError: Cannot read properties of null (reading 'uid'). The uid isn't retrieved by the time the page loads. When I reload localhost from my terminal, the query runs just fine and my desired info is shown, since the auth has loaded.
In an attempt to solve this, I've placed my query and data retrieval inside a useEffect()
useEffect(() => {
const getStories = async () => {
const q = query(storiesCollectionRef, where("authorId", "==", auth.currentUser.uid))
const data = await getDocs(q);
setStoryList(data.docs.map((doc) => ({...doc.data(), id: doc.id})));
};
getStories();
}, [auth]);
I know that giving a useEffect() dependencies will cause it to reload when these dependencies update. I've tried leaving it empty [], putting [auth], and putting [auth.currentUser] as dependecies as per this post, but nothing has worked.
I need to get the uid before my page loads so that the correct information is displayed to the user. I'd appreciate any help!
Edit: Since I couldn't get it working, my temporary solution is to implement my query logic in my map. I would still really appreciate any insight on how to resolve this properly, as getting all the documents and then refining based on uid seems improper.
useEffect(() => {
const getStories = async () => {
//const q = query(storiesCollectionRef, where("authorId", "==", auth.currentUser.uid))
const data = await getDocs(storiesCollectionRef);
setStoryList(data.docs.map((doc) => ({...doc.data(), id: doc.id})));
};
getStories();
}, []);
return(
{storyList.map(story => {
return auth.currentUser.uid === story.authorId ?
<Storybook title={story.title}/>
:
<></>
})}
)
It takes a second for the information to render properly but at least there's no error.