I'm trying to fill an array using the useState Hook. This project is made with Next.js and Tailwind.
In each iteration of the map function I'd like to add an item to the end of the array until there are no items left.
My goal is to have a stateful array that is filled with items so that I can manipulate all the items.
Thanks.
index.js
import { useState } from "react";
import Head from "next/head";
import Image from "next/image";
import requests from "../components/requests";
import Content from "../components/Content";
import Header from "../components/Header";
export const getStaticProps = async () => {
const res = await fetch("https://pokeapi.co/api/v2/pokemon?limit=2000/");
const pokemonData = await res.json();
return {
props: { pokemon: pokemonData },
};
};
export default function Home({ pokemon }) {
return (
<>
<Header />
<main className="flex flex-col items-center justify-center sm:flex-row sm:flex-wrap">
{pokemon.results.map((pokemon) => (
<Content key={pokemon.name} pokemon={pokemon} />
))}
</main>
</>
);
}
Content.js
import React, { useState, useEffect } from "react";
import Image from "next/image";
const Content = ({ pokemon }) => {
const [Pokemon, setPokemon] = useState({ name: [] });
// name.forEach((name) => name[0].toUpperCase() + name.substring(1));
const url = pokemon.url;
const pokemonIndex = url.split("/")[url.split("/").length - 2];
const imageUrl = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${pokemonIndex}.png`;
useEffect(() => {
setPokemon((prevState) => ({
...prevState,
name: prevState.name.concat(pokemon.name),
}));
}, [pokemon]);
console.log(Pokemon);
return (
<div className="p-5">
<h1 className="text-center text-3xl font-bold">{pokemon.name}</h1>
{/* <Image src={Pokemon.imageUrl} width="250" height="250" /> */}
</div>
);
};
export default Content;