I want passing data after fetching that with use effect into my component, after a while i found the problem
export interface IUser {
display_name: string;
id: string;
images: Image[];
}
export interface Image {
url: string;
}
const [userData, setUser] = React.useState<IUser[]>([{
display_name: '',
id: '',
images: [{
url: ''
}]
}]);
const token = useSelector((state: RootStateOrAny) => state.token.value);
const getCurrentUser = async (token: string) => {
try {
const response = await axios.get("https://api.spotify.com/v1/me", {
headers: {
Authorization: `Bearer ${token}`
}
})
return response.data
}
catch (e) {
console.error(e)
}
}
i use async
React.useEffect(() => {
const get = async()=>{
const data = await getCurrentUser(token);
setUser(data)
}
get();
},[])
im using app bar component template from material ui and the problem come from tooltip child component that show avatar
here my code
...
<Box sx={{ flexGrow: 1, justifyContent: 'end' }}>
{console.log(userData)} //this line working and can pass the data
<Tooltip title={userData.images[0].url}> // this line didnt working so if i pass to another child like avatar it cant work too, but if i delete the data code it will work properly
<IconButton onClick={handleOpenUserMenu} sx={{ p: 0 }}>
{/* {console.log(userData.images[0].url)} */}
<Avatar alt="Remy Sharp" src='{}' />
</IconButton>
</Tooltip>
...
</Box>
...
i think the problem come from rendering react, because in the outside of tooltips component it can work but when enter the tooltip component it will render tooltips component first before the useEffect so the data is unavailable
Im stuck for my final project to show profile data in app bar because i cant resolve this problem :V so can anyone help me for this ?? big thanks!
From what I can tell, you've declared userData to be an array.
export interface IUser {
display_name: string;
id: string;
images: Image[];
}
export interface Image {
url: string;
}
...
const [userData, setUser] = React.useState<IUser[]>([{
display_name: '',
id: '',
images: [{ url: '' }],
}]);
In the render return the code is accessing the userData state as though it was an object. console.log(userData) is ok since it's just the entire state value, but userData.images is undefined. Accessing userData.images alone is ok though, it's when the code then attempts to access the 0th index of this undefined value that the error is thrown.
I suspect you meant to access userData[0].images first, then userData[0].images[0].
code
console.log(userData);
...
<Box sx={{ flexGrow: 1, justifyContent: 'end' }}>
<Tooltip title={userData[0].images[0].url}>
<IconButton onClick={handleOpenUserMenu} sx={{ p: 0 }}>
<Avatar alt="Remy Sharp" src='{}' />
</IconButton>
</Tooltip>
...
</Box>
...