Always, Keep in mind that an iterator (in JavaScript) is simply any object that follows the iterator protocol: it has a .next() method that returns items in a sequence until it’s done. The tricky part is that you can’t use array methods like .map() or .forEach() directly on iterators—these methods work on arrays (or array-like structures).
How to iterate over an iterator? To iterate over an iterator more “naturally” in JavaScript, you can either:
Spread it into an array:
js
const arrayFromIterator = [...myIterator];
arrayFromIterator.map(...)
arrayFromIterator.forEach(...)
// Use a for...of loop:
for (const item of myIterator) {
console.log(item);
}
Once you convert or iterate it in a loop, you have the resulting items in a typical JavaScript data structure (e.g., an array) that’s easily consumed by React or other libraries.
For your react code :
function MyComponent() {
const [pokemons, setPokemons] = React.useState([]);
React.useEffect(() => {
fetch("/missionDay")
.then((res) => res.json())
.then((data) => {
// data.message is presumably an array of IDs
// Convert them to the actual Pokemon array
const fetchedPokemons = data.message.map((id) =>
Pokemon.find((pok) => pok.id === id)
);
setPokemons(fetchedPokemons); // store as array
})
.catch((err) => console.error(err));
}, []);
// Then render it easily in the JSX:
return (
<ul>
{pokemons.map((pokemon) => (
<li key={pokemon.id}>{pokemon.name}</li>
))}
</ul>
);
}
Upvote if helpful.