how to select an Array within an api in React?

Asked

Viewed 39 times

1

You guys talking? All right?

I have a problem in my React application with an api, you could help me?

I want to show the names of the Pokemons of an api, but the array that gets the names of the Pokemons is inside "Results" in the "date" of the api, so whenever I try to run the code of "Undefined" as if there was an array for it to read.

I have not yet put the surrender, but how do I warn the this.setState({pokemon: response.data}) that the array is within Results?

example: this.setState({pokemon: response.data"results"})

import api from './api';


class App extends Component{

  state={
    pokemon: [],

  }

  async componentDidMount(){
      const response = await api.get('');
      console.log(response.data);
      this.setState({pokemon: response.data})
  }


  render(){};
}

export default App;
import axios from 'axios';


const api = axios.create({
    baseURL: 'https://pokeapi.co/api/v2/pokemon'
})

export default api;
  • Try to catch it like this: response.data.results

1 answer

1


Based on your text, I believe the result of your api comes like this:

results: [
  {id: 1, name: 'Nome1'},
  {id: 3, name: 'Nome2'},
  {id: 3, name: 'Nome3'},
  {id: 4, name: 'Nome4'}
]

So, in Axios Sponse you can get the data like this:

console.log(response.data.results);

I hope it helps

  • It worked, thanks a lot!!

Browser other questions tagged

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