Struggling with displaying data in my NextJS app.
Data is being fetched from Firebase, and the interface structure is as follows:
export default interface IUser {
name: string;
email: string;
uid: string;
profileImageURL: string;
publicData: {
phone: string;
address: string;
}
}
When accessing users/[id]/page.tsx, data is fetched using the following code:
const [userData, setUserData] = useState({} as IUser);
useEffect(() => {
const fetchData = async () => {
try {
setIsLoading(true);
const fetchedUserData = await fetchUserData(params.id)
.then((data) => {
setUserData(data)
setIsLoading(false);
})
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, []);
While attempting to display the data, everything within publicData
displays correctly, such as name and email. However, trying to access and display userData.publicData.address
results in an error
TypeError: Cannot read properties of undefined (reading 'address')
Unsure about the cause of this issue, as the console shows no problem with the data. Maybe it's related to the User interface?
Appreciate any tips or solutions you can provide. Thank you!
UPDATE Here's a screenshot of the firebase structure https://i.sstatic.net/WxyNTSvw.png
Also including the code for 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;
};