typescriptfirebasenext.js

TypeError: Cannot read properties of undefined (Getting data from firebase)


having some trouble while displaying data in my NextJS app.

I'm fetching data from Firebase, the interface looks like so:

export default interface IUser {
  name: string;
  email: string;
  uid: string;
  profileImageURL: string;
  publicData: {
    phone: string;
    address: string;
  }
}

When i'm accessing users/[id]/page.tsx i'm fetching the data:


const [userData, setUserData] = useState({} as IUser);

    useEffect(() => {

      const fetchData = async () => {
        try {
          setIsLoading(true);
          const IUser = await fetchUserData(params.id)
          .then((data) => {
            setUserData(data)
            setIsLoading(false);
          })
        } catch (error) {
          console.error('Error fetching data:', error);
        }
      };
    
      fetchData();
    }, []);

When i try to display the data anything that is not in publicData is displayed without a problem, that being name, email, etc. When i try to access and display userData.publicData.address, i get an error TypeError: Cannot read properties of undefined (reading 'address')

Not really sure what is the issue here, since console logs do show the data without a problem, thought it maybe related to the User interface.

Thanks in advance for all the tips and solutions.

UPDATE Adding a screenshot of the firebase structure firebase structure

Also adding code of fetchUserData

import IUser from "../interfaces/User";
import { getCache, setCache } from "./cache";

export const fetchUserData = async (uid: string): Promise<IUser> => {

    const cacheKey = 'userData_' + uid;
    const cachedData = getCache(cacheKey);

  if (cachedData) {
    console.log('Returning cached data:', cachedData);
    return cachedData as IUser;
  }

    const response = await fetch('https://dev/auth/user?id=' + uid,
        {
        method: 'get',
        headers: {
            'Content-type': 'application/json'
        }
    })
    if (!response.ok) {
        throw new Error("Failed to fetch user data");
    }
const data: IUser = await response.json();
console.log('Fetched data:', data);
setCache(cacheKey, data);

return data;
};

Solution

  • This is happening because where ever you are trying to use display data or use data. You haven't checked weather data is available or not. fetching data takes some time. so you must add condition where before using the data, you should check weather data is fetched or not. For example: In react when rendering you can do

       userData?.length > 0 && userData?.map(user => {
               //what ever data you are trying to render
    });
    

    And not forget to use '?' before dot or otherwise you will see error screen. At least your app won't crash. Hope that will help you. Thanks