score:1

Accepted answer
 const handleKeyStroke = (e) => {
    switch (e.keyCode) {
      // GO LEFT
      case 37:
        break;
      // GO RIGHT
      case 39:
        console.log("RIGHT", startId);
        setStartId(prev=>prev + 1);
        break;
      default:
        break;
    }
  };

score:0

const POKE_API_URL = "https://pokeapi.co/api/v2/pokemon";

const Carousel = ({ handleKeyDown, pokemonUrls, startId }) => (
  <div tabIndex="0" onKeyDown={handleKeyDown}>
    <img alt="pokemon" src={pokemonUrls[startId]} />
  </div>
);

export default function App(props) {
  const [pokemonUrls, setPokemonUrls] = useState([]);
  const [startId, setStartId] = useState(0);
  const [endId, setEndId] = useState(0);

  const handleKeyDown = (e) => {
    switch (e.keyCode) {
      // GO LEFT
      case 37:
        if (startId - 1 >= 0) {
          setStartId((prev) => prev - 1);
        }
        break;
      // GO RIGHT
      case 39:
        if (startId < pokemonUrls.length - 1) {
          setStartId((prev) => prev + 1);
        }
        break;
      default:
        break;
    }
  };

  useEffect(() => {
    async function fetchPokemonById(id) {
      const response = await fetch(`${POKE_API_URL}/${id}`);
      const result = await response.json();
      return result.sprites.front_shiny;
    }

    async function fetchNpokemon(n) {
      let pokemon = [];

      for (let i = 0; i < n; i++) {
        const pokemonUrl = await fetchPokemonById(i + 1);
        pokemon.push(pokemonUrl);
      }
      setPokemonUrls(pokemon);
    }

    fetchNpokemon(5);
  }, []);

  return (
    <div className="App">
      <Carousel
        handleKeyDown={handleKeyDown}
        pokemonUrls={pokemonUrls}
        startId={startId}
      />
    </div>
  );
}

Related Query

More Query from same tag