Im new in react development and i dont understand why this code dont show pokemon.name
on the first h1 tag:
import './Container.css';
function Container ({ id }) {
const getPokemon = async(id) => {
const url = `https://pokeapi.co/api/v2/pokemon/${id}`;
const res = await fetch(url);
return await res.json();
}
const pokemon = getPokemon(id);
return (
<div className="container">
<h1>{pokemon.name}</h1>
<h1>test</h1>
</div>
);
}
export default Container;
CodePudding user response:
Because getPokemon
returns a Promise, not data. And that Promise
is never awaited.
More specific to React in your case, however...
You don't want to try to await and return the value, you want to make use of state in React.
Declare a state value at the start of your component:
const [pokemon, setPokemon] = useState({});
Update it in your asynchronous operation:
const res = await fetch(url);
setPokemon(await res.json());
Invoke your operation when the component first loads (or any time id
changes):
useEffect(() => {
getPokemon(id);
}, [id]);
Then you'll find that the component first renders with no data, then re-renders after the AJAX operation so it can use the new data. Updating state triggers a React component to re-render.