简体   繁体   中英

How do I ignore data if it doesn't exist in an API call?

If I make this call but the pokemon I've entered doesn't have a second type I get this error message:

在此处输入图像描述

Is it possible to make an if statement within the useState hook that I've named setPokemon ?

If so, how can I do that or how can I get through this?

 import Axios from "axios";
    import React, { useState } from "react";
    import "./SearchPokemon.css";

function PK() {
  const api = Axios.create({
    baseURL: "https://pokeapi.co/api/v2/",
  });

  const [pokemon, setPokemon] = useState({});
  const [pokemonDescription, fetchDescription] = useState({});
  const [evolution, pokemonEvolution] = useState({});

  const searchPokemon = () => {
    api.get(`pokemon/charmander`).then((response) => {
      setPokemon({
        name: response.data.name,
        height: response.data.height,
        weight: response.data.weight,
        img: response.data.sprites.front_default,
        id: response.data.id,
        type: response.data.types[0].type.name,
        type2: response.data.types[1].type.name,
      });

      api.get(`pokemon-species/${response.data.id}/`).then((response) => {
        fetchDescription({
          entry: response.data.flavor_text_entries[0].flavor_text,
          evolution: response.data.evolution_chain.url,
        });
        api.get(`${response.data.evolution_chain.url}`).then((response) => {
          pokemonEvolution({
            evolution: response.data.chain.evolves_to[0].species.name,
          });
        });
      });
    });
  };

  return (
    <div>
      <div className="main">
        <h1 style={{ textTransform: "capitalize" }}>{pokemon.name}</h1>
        <h1>No. {pokemon.id}</h1>
        <img src={pokemon.img} alt="" />
      </div>

      <div className="info">
        <h3 style={{ textTransform: "capitalize" }}>
          Type: {pokemon.type} {pokemon.type2}
        </h3>
        <h3>Height: {pokemon.height * 10} Cm</h3>
        <h3>Weight: {pokemon.weight / 10} Kg</h3>
      </div>

      <div className="desc">
        <div className="desc-info">
          <h3 style={{ textTransform: "capitalize" }}>
            {pokemonDescription.entry}
          </h3>
        </div>
      </div>

      <h1 style={{ textTransform: "capitalize" }}>
        Evolution: {evolution.evolution}
      </h1>
      <button onClick={searchPokemon}>Click me</button>
    </div>
  );
}


export default PK;

If we first look at your error, the index 1 of your types array from your api response data is not defined. Therefore, when you try to access, it throws.

When you are not certain of the response of your api, you can use a combination of optional chaining and setting default values for that property. This way, your code won't break.

In your example, I believe you could do something like:

 const response = { data: { types: [] } }; console.log(response.data.types[1]?.type.name?? "pick a value or leave an empty string"); // type2: response.data.types[1]?.type.name?? ""

Notice the question mark I've added right after the index 1 of your expected types array. This symbol allows for optional chaining.

Then we use Nullish coalescing operator (??).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM