Fetch Api learning 1

Tue, Jun 9, 2020 One-minute read

Fetch Api learning 1 (easy)

PokeAPI

const apiData = {
  url: "https://pokeapi.co/api/v2/",
  type: "pokemon",
  id: "1",
};

const apiUrl = `${apiData.url}${apiData.type}/${apiData.id}`;

console.log(apiUrl);

// https://pokeapi.co/api/v2/pokemon/1

now let’s learn to write a much clear code:更加简洁的 code

const apiData = {
  url: "https://pokeapi.co/api/v2/",
  type: "pokemon",
  id: "1",
};

const { url, type, id } = apiData;
const apiUrl = `${url}${type}/${id}`;

console.log(apiUrl);

// https://pokeapi.co/api/v2/pokemon/1 now about fetch

fetch(apiUrl).then((data) => data.json());

fetch(apiUrl).then((data) => console.log(data.json()));
// fetch will return a Promise holds data
fetch(apiUrl)
  .then((data) => data.json())
  .then((pokemon) => console.log(pokemon)); //data,pokemon, you can pick whatever name you like

print the data from Promise

fetch(apiUrl)
  .then((data) => data.json())
  .then((pokemon) => generateHtml(pokemon));

const generateHtml = (data) => {
  console.log(data);
  const html = `
      <div class = "name">${data.name} </div>
      <img src = ${data.sprites.front_default}>
      <div class = "details">
      <span>Height: ${data.height}</span>
      <span>Weight: ${data.weight}</span>

      </div>
    `;
  const pokemonDiv = document.querySelector(".pokemon");
  pokemonDiv.innerHTML = html;
};

done~~~!