JAVASCRIPT - Star Wars API -Promise Return

Asked

Viewed 50 times

0

my problem is that I can’t return the results['name'] of the api request. When I click on the button it returns the Response.data with the following response

['Object, Object'] and when I Seto data.Results returns the error : scripts.js:15 Uncaught (in Promise) Typeerror: Cannot read Property 'name' of Undefined at scripts.js:15

The idea is : once I click the button, I return to a random planet.

If anyone can help I’d appreciate it.

let button = document.querySelector('#botao');
let name   = document.querySelector('#Name');

function getPlanet() {

    let randomNumber = Math.floor(( Math.random() * 88 ) + 1 )
    let apiUrl = 'https://swapi.co/api/planets/' + randomNumber

        // integrando API para adicionar a função getPlanet;
    axios.get  (apiUrl).then(( async function ( response ) {
        console.log(response)
      updateInfo ( await response.data.results['name'])
    } ))    
}
function updateInfo(data) {
    name.innerText = data.results
}
        // Evento Click;
button.addEventListener('click', getPlanet);

1 answer

1


Your way of using the asynchronous request is slightly wrong try so other notes, after name, have no Results array within the return of the api see

{ name: 'Saleucami',
  rotation_period: '26',
  orbital_period: '392',
  diameter: '14920',
  climate: 'hot',
  gravity: 'unknown',
  terrain: 'caves, desert, mountains, volcanoes',
  surface_water: 'unknown',
  population: '1400000000',
  residents: [],
  films: [ 'https://swapi.co/api/films/6/' ],
  created: '2014-12-10T13:47:46.874000Z',
  edited: '2014-12-20T20:58:18.450000Z',
  url: 'https://swapi.co/api/planets/19/' }

So you can’t do Replay.data.Results['name'] and inside updateInfo, you don’t have to access Replying either.

let button = document.querySelector('#botao');
let name   = document.querySelector('#Name');

async function getPlanet() {
    try{
       let randomNumber = Math.floor(( Math.random() * 88 ) + 1 )
       let apiUrl = 'https://swapi.co/api/planets/' + randomNumber

        // integrando API para adicionar a função getPlanet;
       const response = await axios.ge(apiUrl)
       updateInfo(response.data.name)
    }
    catch(error => console.log(error))    
}
function updateInfo(name) {
    name.innerText = name
}
        // Evento Click;
button.addEventListener('click', getPlanet);

Browser other questions tagged

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