I am having an error mapping a API request from a useState.
My fetch works perfectly and returns an array of objects that I then put into my useState. After that I try to map my useState out so that I only console.log the name field. I am using the code below.
const help = mygenres.map((elem) => console.log(elem.name));
What I get is an array with zero objects
Then, without refreshing, I use the code below
const help = mygenres.genres.map((elem) => console.log(elem.name));
And everything works. I get a list of my genres displayed in my console.log
However when I refresh the page, I get a bunch of errors. The only way to fix it is to go back to the first code, save, then again update it to the second code so that it works again until the next time I refresh the page.
Any idea why this is happening and how to fix it? Seems to be working when re-rednering but not when mounting. Does it have something to do with the way my useEffect was setup?
Below is what my fetch returns and what is put into my use state
genres: Array(19)
0: {id: 28, name: 'Action'}
1: {id: 12, name: 'Adventure'}
2: {id: 16, name: 'Animation'}
3: {id: 35, name: 'Comedy'}
4: {id: 80, name: 'Crime'}
5: {id: 99, name: 'Documentary'}
6: {id: 18, name: 'Drama'}
7: {id: 10751, name: 'Family'}
8: {id: 14, name: 'Fantasy'}
9: {id: 36, name: 'History'}
10: {id: 27, name: 'Horror'}
11: {id: 10402, name: 'Music'}
12: {id: 9648, name: 'Mystery'}
13: {id: 10749, name: 'Romance'}
14: {id: 878, name: 'Science Fiction'}
15: {id: 10770, name: 'TV Movie'}
16: {id: 53, name: 'Thriller'}
17: {id: 10752, name: 'War'}
18: {id: 37, name: 'Western'}
Below is my complete code
import React from "react";
import { useState, useEffect } from "react";
export default function Genrenavbar() {
const [mygenres, setMygenres] = useState([]);
useEffect(() => {
async function APIrequests() {
const response = await fetch(
`https://api.themoviedb.org/3/genre/movie/list?api_key=${process.env.REACT_APP_MY_TEST_API}&language=en-US`
);
const movie = await response.json();
console.log(movie);
setMygenres(movie);
console.log(mygenres);
}
APIrequests();
}, []);
const help = mygenres.genres.map((elem) => console.log(elem.name));
return (
<div>
<h1>Hello</h1>
</div>
);
}
This is a bit more robust;
import React, { useState, useEffect, useMemo } from "react";
export default function Genrenavbar() {
const [mygenres, setMygenres] = useState([]);
useEffect(() => {
(async () => {
try {
const response = await fetch(
`https://api.themoviedb.org/3/genre/movie/list?api_key=${process.env.REACT_APP_MY_TEST_API}&language=en-US`
);
const movie = await response.json();
setMygenres(movie);
} catch (error) {
// handle errors here
console.log({ error });
}
})();
}, []);
const help = useMemo(() => mygenres?.genres?.map((elem) => elem?.name), [mygenres]);
console.log(help);
return (
<div>
<h1>Hello</h1>
</div>
);
}