Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

201
Visualizações
Mapping from useState question - react/Js

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>
  );
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda