Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
React Hook useEffect async fetch data not passing to tooltip material ui component

I want passing data after fetching that with use effect into my component, after a while i found the problem

Here some of my code

userData Types (UPDATED)

export interface IUser {

display_name:  string;
  id:            string;
  images:        Image[];
}

export interface Image {
  url:    string;
}

UseState (UPDATED)

const [userData, setUser] = React.useState<IUser[]>([{
display_name: '',
id: '',
images: [{
  url: ''
}]

}]);

const token = useSelector((state: RootStateOrAny) => state.token.value);

GetCurrentUser function

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)
}


}

useEffect function

i use async

React.useEffect(() => {
const get = async()=>{
  const data = await getCurrentUser(token);
  setUser(data)
}
get();

},[])

My main component

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>
...

The Error

enter image description here

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!

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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>
...
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda