Mintee
Mintee

Reputation: 835

Next.js: Cannot read properties of undefined (reading 'indexOf')

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();
  }, []);

enter image description here

Upvotes: 1

Views: 1914

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598740

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

Upvotes: 3

Related Questions