Home > Net >  reaching data inside an object while using map
reaching data inside an object while using map

Time:06-13

I'm sorry in advance for my ignorance, But its been a while since I coded, and I need a little help with this basic thing, Im trying to reach name, and display it on screen when I click a button, but i just can't figure it out, can u help me and explain what you did so I can know for the next time? looked manuals and articles about how to do it but you guys are just simply better. my code:

functional (pokeAPI.ts):

import React from "react";
import axios from 'axios'


export const getPokemon=()=>{
    axios.get("https://pokeapi.co/api/v2/pokemon?limit=151").then((response)=>{
response.data.results.map((cont : string,index : number) => console.log(
        cont
      ));
    })

  }

app.tsx:

   import './App.css';
    import React from 'react';
    import {getPokemon} from './func/pokeAPI';
    
    function App() {
    
      return (
    <div>
    <button onClick={getPokemon}>Cli</button>
    </div>
    
      );
    }
    
    export default App;

CodePudding user response:

Here you go! Since you're using typescript, I created a PokemonData interface as well.

import React from 'react'
import axios from 'axios'
import "./styles.css";

interface PokemonData {
  name: string
  url: string
}


export default function App() {
  const [pokemons, setPokemons] = React.useState<null|PokemonData[]>(null)

  const onClick = async () => {
    axios.get("https://pokeapi.co/api/v2/pokemon?limit=151").then((response)=>{
      console.log(response.data.results)
      setPokemons(response.data.results)
     })
  }

  return (
    <div className="App">
      <button onClick={onClick}>Get pokemon</button>
     {pokemons?.map((pokemon) => (
       <div key={pokemon.name}>
         <p>{pokemon.name}</p>
         <p>{pokemon.url}</p>
       </div>
     ))}
    </div>
  );
}

I also wrote a Codesandbox here so you can check it out

Edit: Another version of the return statement if optional chaining isn't supported on your project's version

 return (
    <div className="App">
      <button onClick={onClick}>Get pokemon</button>
     {pokemons && pokemons.map((pokemon) => (
       <div key={pokemon.name}>
         <p>{pokemon.name}</p>
         <p>{pokemon.url}</p>
       </div>
     ))}
    </div>
  );
}
  • Related