0
I am consuming the Deezer API, using useEffect and useState in Reactjs to list a particular track (an example), but when using the .map
, to render, the following error is returned:
TypeError: musicas.map is not a function
After researching, I thought it was because of the asynchronicity and the component was being rendered before the data arrived, but I’m using async await to consume the API.
Code:
import React from 'react';
import { Container } from '../../styles/GlobalStyles';
import { CardContainer } from './styled';
import axios from '../../services/axios';
export default function Home() {
const [musicas, setMusicas] = React.useState([]);
async function getData() {
const response = await axios.get('/track/3135556');
setMusicas(response.data);
}
React.useEffect(() => {
getData();
}, []);
React.useEffect(() => {}, [musicas]);
if (musicas.length === 0) {
return (
<Container>
<h1>Carregando</h1>
<hr />
</Container>
);
}
return (
<Container>
<h1>Home</h1>
<hr />
{musicas.map((musica) => (
<CardContainer key={String(musica.id)}>{musica.title}</CardContainer>
))}
</Container>
);
}
When I comment on the part of the code you are listing (.map), I give one console.log(musicas)
, in useEffect, it returns to me the data normally in the console, so the API address is correct and it is getting the data.
React.useEffect(() => {console.log(musicas)}, [musicas]);
I tried to list with and without the if (musicas.length === 0)
, but makes the same mistake.
I believe that despite the assync await, the component is requiring the data before it has arrived, if that’s what it is, I don’t know how to fix it. If anyone knows how to fix whatever’s causing it, I’d appreciate it.
is not an array is a simple object!
– novic
Since the API response is an object I believe it would solve the problem
setMusicas([response.data]);
but are you sure you’re hitting the request at the correct endpoint? it seems to me that you are searching the data of only one song instead of receiving a list with several.– Gabriel José de Oliveira
@Gabrieljosédeoliveira worked. So, I was just doing it as an example to facilitate when I was going to call on
.map
. In case really is a single track, just wanted to be rendered something, but expensive, despite being a very simple resolution, it worked, thank you very much.– Igor Noia Silva