Reputation: 443
I am the error bellow.
Uncaught (in promise) TypeError: Cannot read property 'map' of undefined
when trying to execute the map function below, where the link that simulates the API is http://www.mocky.io/v2/5db88c413b00004f0b35f1f1:
state = {
name: 'Teste II',
produto: null,
alternativas: null,
atributos: null,
loading_produto: true,
loading_alternativas: true,
loading_atributos: true,
showPopup: false,
};
constructor( props ) {
super( props );
}
async componentDidMount(){
const url = "http://www.mocky.io/v2/5db88c413b00004f0b35f1f1";
const response = await fetch(url);
const data = await response.json();
this.setState({produto: data.suggestions[0], loading_produto: false})
this.setState({alternativas: data.choices, loading_alternativas: false})
this.setState({atributos: data.suggestions[0].attributes, loading_atributos: false})
console.log(this.state.produto.product_data.title);
}
render() {
const lista_alternativas = this.state.alternativas;
const lista_atributos = this.state.atributos;
if(!this.state.loading_atributos){
this.atributos = lista_atributos.map((description, key) => {
console.log('chegou aqui');
return <li key={description.id}>{description.description}</li>
});
}
return (
What is wrong?
Upvotes: 0
Views: 40
Reputation: 857
Check the response of that URL, you're setting the state value "atributos" to data.suggestions[0].attributes (which doesn't exist).
You might want to change that to data.suggestions[0].product_data.attributes.
More specifically, change your componentDidMount function to this:
async componentDidMount(){
const url = "http://www.mocky.io/v2/5db88c413b00004f0b35f1f1";
const response = await fetch(url);
const data = await response.json();
this.setState({produto: data.suggestions[0], loading_produto: false})
this.setState({alternativas: data.choices, loading_alternativas: false})
this.setState({atributos: data.suggestions[0].product_data.attributes, loading_atributos: false})
console.log(this.state.produto.product_data.title);
}
Upvotes: 1
Reputation: 497
Try setting the initial state of atributos to an empty array instead of null:
state = {
name: 'Teste II',
produto: null,
alternativas: null,
atributos: [],
loading_produto: true,
loading_alternativas: true,
loading_atributos: true,
showPopup: false,
};
Upvotes: 1