Spotify API: this.state.data.map is not a Function

Asked

Viewed 76 times

0

I am trying to pass the data from the api to a child component, but always giving this error when I type the name of the singer in the input, because I want to fetch every letter typed, not just after completing the name.

The data is coming in normally, by console.log I could see that they are all there, so I believe it is really a problem in . map

import React, { Component } from 'react';
import ItemPage from './apiUnica'; 
import querystring from 'querystring'; 

class api extends Component {
constructor(props){
    super(props);
    this.state = {data: [], isLoaded: false, display_name: '' }
}

componentDidMount(){
    const accessToken = window.location.search.slice(14);
    fetch('https://api.spotify.com/v1/me', {headers: {'Authorization': 'Bearer '+accessToken}})
        .then(response => response.json())
        .then(data => this.setState({display_name: data.display_name, isLoaded: true}))
}

async updateResult(){
    const artist = document.getElementById("singer").value;
    const accessToken = window.location.search.slice(14);
    await fetch('https://api.spotify.com/v1/search?'+querystring.stringify(
        {q: artist,
        type: 'artist',
        limit: '5'
    }), 
    {headers: {'Authorization': 'Bearer ' + accessToken}})
            .then(response => response.json())
            .then(data => this.setState({
                 data: data.artists
            }))     
    if(this.state.data){
    console.log(this.state.data)
    }
}

render(){
    return(
        <div>       
            <div>
                <input type="text" onChange={this.updateResult.bind(this)} id="singer"/>
                {!this.state.isLoaded ? <h1>Carregando</h1> : <h1>Bem vindo {this.state.display_name}</h1>}
                {!this.state.data ? 'missing data'  : this.state.data.map(item => <ItemPage singerName={item.artists.name} />)}
            </div>
        </div>
    );
}

1 answer

0


According to the official documentation of Spotify the type of variable of data.artists that you refer to when you are modifying the state of the component is actually an object, but what you want is the property items inside data.artists how is it possible to see in this example.

What you should do when modifying state is:

this.setState({data: data.artists.items});
  • Really that was it, after I saw that there were more things beyond the array, and so the MAP would not work because it is prepared to work with just that kind of information.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.