The code below initially works but once I reload the page I get TypeError: Cannot read properties of undefined (reading 'indexOf')
.
const [folders, setFolders] = useState([]);
const [user] = useAuthState(auth);
const folderColRef = collection(db, "UsersData", user?.uid, "Folders");
useEffect(() => {
const getFolders = async () => {
const userData = await getDocs(folderColRef);
setFolders(userData.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
};
getFolders();
}, []);
This typically means that you're passing undefined
to the collection
functions, which is not allowed. In your code that means that user
is null
, which is actually the normal behavior when the page first loads (as restoring the user's authentication state requires an asynchronous call to the server).
My guess is that you'll need to have the effect depend on the user variable, and then handle the null
/ undefined
inside of that:
const [user] = useAuthState(auth);
useEffect(() => {
if (!user) return; // 👈 Add this line
const folderColRef = collection(db, "UsersData", user!.uid, "Folders"); // 👈 Move this line
const getFolders = async () => {
const userData = await getDocs(folderColRef);
setFolders(userData.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
};
getFolders();
}, [user]); // 👈 Add a dependency here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.