I have this component that was working fine, i decided to try and build it further by adding the getMoves
function but the results I'm getting are not as expected.
The four console.log()
s in the code below, at the bottom of the getMoves
function basically show the problem i'm having.
Even though both moves
and monz[0]
seem to be correct in the console, moves.monz[0]
gives the error 'Cannot read properties of undefined (reading '0')'
import React from "react";
import { useState } from "react";
const Teams = ({ teams }) => {
if (!teams) {
return null;
}
let monz = [];
const [moves, setMoves] = useState([]);
const [league, setLeague] = useState("default");
function handleChange(e) {
setLeague(e.target.value);
}
const getMoves = async () => {
const req = await fetch(`/api/move-data/${league}`);
const json = await req.json();
setMoves(json);
console.log(moves); // this works
console.log(moves.charizard); // this works
console.log(monz[0]); // this works - prints 'charizard'
console.log(moves.monz[0]); // this doesn't work?!
};
let pokemap = teams.slice(1).map((team, index) => (
<React.Fragment key={index}>
<div className="MainDiv">
{" "}
<div>{team[0].bout}</div>{" "}
<div class="container">
<br />
{Array.isArray(team) &&
team.slice(1).map((pokemon) => (
<React.Fragment key={pokemon.pokemon}>
<div class="child">
<img src={pokemon.sprite} />
<div style={{ display: "none" }}>
{monz.push(pokemon.pokemon.toLowerCase())}
</div>
<p>{pokemon.pokemon}</p>
</div>
</React.Fragment>
))}
</div>
<div>
{team[0].wins && "Score: "} <br />{" "}
{team[0].wins && team[0].wins + "-"}
{team[0].wins && 3 - team[0].wins}
</div>
<select value={league} onChange={handleChange}>
<option value="default" selected disabled hidden>
Pick a league
</option>
<option value="Great">Great</option>
<option value="Ultra">Ultra</option>
<option value="Master">Master</option>
<option value="Field">Field</option>
</select>
<button onClick={getMoves}>Click</button>
{/* {moves.monz[0].Name} - this doesn't work */}
</div>
</React.Fragment>
));
if (!teams[0]) {
return null;
}
return (
<>
<div className="bold">Win Rate: {teams[0].winrate}%</div>
<div>{pokemap}</div>{" "}
</>
);
};
export default Teams;