Home > Enterprise >  Using response.status in React to display HTML
Using response.status in React to display HTML

Time:10-01

I want to use an if statement to only return the moves array if I don't get a 404 error in the getPokemon fetch call. I am trying to display some other HTML if there are no values in the array.

This is my code:

  const getPokemon = async (event) => {
    event.preventDefault();
    const response = await fetch("https://pokeapi.co/api/v2/pokemon/"   search);
    const data = await response.json();
    const responseStatus = response.status

  };

    <div>
      <h1>Pokemon</h1>
      <form onSubmit={getPokemon}>
        <input
          type='search'
          placeholder='search pokemon'
          onChange={searchChange}
        ></input>
        <input type='button' value='Search!' />
      </form>

      <p>moves</p>
      {moves.map((move) => (
        <ul>
          <li>
            <p>{move}</p>
          </li>
        </ul>
      ))}
    </div>

};

CodePudding user response:

You can use a state for that:

import React from "react";
const App = () => {
  const [renderMovies, setRenderMovies] = React.useState(false);
  
  const getPokemon = async (event) => {
    event.preventDefault();
    const response = await fetch("https://pokeapi.co/api/v2/pokemon/"   search);
    const data = await response.json();
    setRenderMovies(response.status !== 404);
  };
  
  return (
    <div>
      <h1>Pokemon</h1>
      
      <form onSubmit={getPokemon}>
        <input
          type='search'
          placeholder='search pokemon'
          onChange={searchChange}
        ></input>
        <input type='button' value='Search!' />
      </form>
      
      <p>moves</p>
      
      {renderMovies ? moves.map((move) => (
        <ul>
          <li>
            <p>{move}</p>
          </li>
        </ul>
      )) : <div>Some other code...</div>}
    </div>
 
  )
}

Also, read more about conditional rendering.

CodePudding user response:

You should use useState and check response status === 200

const getPokemon = async (event) => {
const [movies, setMovies] = useState([]);
const [search, setSearch] = useState('');
event.preventDefault();
const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${search}`);
const data = await response.json();
if(response.status === 200) { // 200 always good 
  setMovies(data)
}

return (
<div>
  <h1>Pokemon</h1>
  <form onSubmit={getPokemon}>
    <input
      type='search'
      placeholder='search pokemon'
      value={search}
      onChange={e => setSearch(e.target.value)}
    ></input>
    <input type='button' value='Search!' />
  </form>

  <p>moves</p>
  <ul>
    {
      movies.lenght > 0 ? 
       (movies?.map((movie) => <li key={movie.id}><p>{movie?.title}</p></li>)
     : <h2>Loading...</h2>
    }
 </ul>
</div>
)
}
  • Related