Reputation: 21
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.
Upvotes: 2
Views: 128
Reputation: 528
You should delay running the query until auth
is available. Currently you are trying to run the query when auth is not defined and hence getting the TypeError.
If uid of currentUser coming from auth is not defined, stories array will simply be an empty array and you should just have to deal with that particular case. You could do something like this:
...
const [storyList, setStoryList] = useState([]);
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})));
};
auth.currentUser.uid && getStories();
}, [auth.currentUser.uid]);
return (
storyList?.length > 0 && storyList.map(list => ...)
)
...
Upvotes: 1