I am trying to recreate a simple pokedex app in react that I made in vanilla javascript. I’m trying to get more API practice, but keep running into this error in the console: “Warning: A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.”
I tried making my states an empty array and then tried an empty object, but I am still getting the same error message. Any help would be appreciated.
This is the code I have written so far:
import { useState, useEffect } from "react";
import PokemonDetails from "./PokemonDetails";
import Paper from "@mui/material/Paper";
import InputBase from "@mui/material/InputBase";
import IconButton from "@mui/material/IconButton";
import SearchIcon from "@mui/icons-material/Search";
export default function PokemonData() {
const [searchInput, setSearchInput] = useState("");
const [pokemonData1, setPokemonData1] = useState(null);
const [pokemonData2, setPokemonData2] = useState(null);
useEffect(() => {
const fetchData1 = () =>
fetch(
`https://pokeapi.co/api/v2/pokemon/${searchInput.toLowerCase()}`
).then((response) => response.json());
const fetchData2 = () =>
fetch(
`https://pokeapi.co/api/v2/pokemon-species/${searchInput.toLowerCase()}`
).then((response) => response.json());
// Using Promise.all to wait for both requests to complete
Promise.all([fetchData1(), fetchData2()])
.then(([result1, result2]) => {
setPokemonData1(result1);
setPokemonData2(result2);
})
.catch((error) => {
console.error("Error fetching data:", error);
});
}, []);
// SEARCH POKEMON
const onSearch = (e) => {
e.preventDefault();
setSearchInput(e.target.value);
};
return (
<div>
<Paper
component="form"
onSubmit={onSearch}
sx={{ p: "2px 4px", display: "flex", alignItems: "center", width: 400 }}
>
<InputBase
sx={{ ml: 1, flex: 1 }}
placeholder="Search Pokémon"
inputProps={{ "aria-label": "search pokémon" }}
value={searchInput}
onChange={onSearch}
/>
<IconButton
type="button"
onClick={onSearch}
sx={{ p: "10px" }}
aria-label="search"
>
<SearchIcon />
</IconButton>
</Paper>
{/* <PokemonDetails pokemon={pokemonData1} /> */}
<h1>Pokemon data from Endpoint 1:</h1>
<pre>{JSON.stringify(pokemonData1, null, 2)}</pre>
<h1>Pokemon data from Endpoint 2:</h1>
<pre>{JSON.stringify(pokemonData2, null, 2)}</pre>
</div>
);
}```