Object key is not recognized after using fetch

Asked

Viewed 52 times

0

The console indicates a wrong saying Uncaught Typeerror: Cannot read Property 'name' of Undefined. within the scope of the function in which API access can access name and other keys.

the code:


function swapiGet(params){
    const url = `https://swapi.dev/api/${params}`;
    fetch(url)
    .then(response => response.json())
    .then(json =>  json)
    
    
    
}
function preencherAssets(){
   personagens.innerHTML =  swapiGet("people/1/").name;
   console.log('primeiro')

}
preencherAssets();

Does anyone know why and how to fix it? I started to study Names and consume Apis recently.

1 answer

2

You have two problems in the roles you presented:

  1. At no time do you return the value in your function swapiGet;
  2. The return of fetch is a Promise, so you should wait for it before using.

const swapiGet = (params) => {
  const url = `https://swapi.dev/api/${params}`;

  return fetch(url)
    .then(response => response.json());
};

const preencherAssets = ({
  name,
}) => {
  personagens.innerHTML = name;
  console.log('primeiro');
};

swapiGet('people/1/').then(preencherAssets);
<span id="personagens"></span>


Learn more about Promises in the answers to the following questions::

Browser other questions tagged

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