I can’t get specific data from the Json API using Next with React js

Asked

Viewed 19 times

-1

I am using this API https://akabab.github.io/superhero-api/api/ and I can even get the data of all the characters with the call https://akabab.github.io/superhero-api/api/all.json, but when I make a call from a specific character I cannot do the data processing of this character.

My code:

import React, {Component} from "react";
import "./App.css"
import api from "./Services/api";

class App extends Component{
  
  state = {
    heroes: [],
    id: "1",
  }

  async componentDidMount(){
    const response = await api.get(`/id/${this.state.id}.json`)

    this.setState({heroes: response.data})
  }
  
  
  render(){

    const { heroes } = this.state;

    return(
      <div>
        <h1>Super heros</h1>
        {heroes.map(heroes => (
          <div key={heroes.id}>
            {heroes.name}
          </div>
        ))}
      </div>
    )
  }
}

export default App;

When I make the specific call the API returns:

{
  "id": 1,
  "name": "A-Bomb",
  "slug": "1-a-bomb",
  "powerstats": {
    "intelligence": 38,
    "strength": 100,
    "speed": 17,
    "durability": 80,
    "power": 24,
    "combat": 64
  },

  "appearance": {
    "gender": "Male",
    "race": "Human",
    "height": [
      "6'8",
      "203 cm"
    ],
    "weight": [
      "980 lb",
      "441 kg"
    ],
    "eyeColor": "Yellow",
    "hairColor": "No Hair"
  },
  • This return is not an array, you will not be able to do heroes.map. Or you change the code to treat it as having only one hero or you save in the state as array: this.setState({ heroes: [response.data] }) (this second alternative, despite changing the code less, is not ideal, if this component has the responsibility to represent a single hero)

  • Thank you very much, helped me more your answer brother. Ps: What a quick reply kkkkkkkkkkkkkkk

No answers

Browser other questions tagged

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