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

85
Visualizações
How to return an object property from an array of objects in react

I have an array of object and I need to get a single property, but it's returning undefined and have no idea why. Does anyone know how to solve?

  const [questions, setQuestions] = useState({});
  const [index, setIndex] = useState(0);
  
  async function handleQuestions() {
    const fetchQuestions = await fetchTriviaApi();
    setQuestions(fetchQuestions.results);
  }

  useEffect(() => {
    handleQuestions();
  }, []);

Return of questions:

    (5) [{…}, {…}, {…}, {…}, {…}]
0: {category: 'Entertainment: Music', type: 'boolean', difficulty: 'medium', question: 'Rapper Snoop Dogg's real name is 'Cordozar Calvin Broadus, Jr.'.', correct_answer: 'True', …}
1: {category: 'Entertainment: Video Games', type: 'multiple', difficulty: 'medium', question: 'Which of these "Worms" games featured 3D gameplay?', correct_answer: 'Worms 4: Mayhem', …}
2: {category: 'Vehicles', type: 'multiple', difficulty: 'easy', question: 'What UK Train does NOT go over 125MPH?', correct_answer: 'Sprinter', …}
3: {category: 'Entertainment: Video Games', type: 'boolean', difficulty: 'medium', question: 'Tony Hawk's Pro Skater was released in 1999.', correct_answer: 'True', …}
4: {category: 'Entertainment: Video Games', type: 'boolean', difficulty: 'hard', question: 'In The Witcher 3, the Zoltan Chivay Gwent card can be found under the Hanged Man's Tree.', correct_answer: 'True', …}
length: 5

Return of questions[index]:

{category: 'Entertainment: Music', type: 'boolean', difficulty: 'medium', question: 'Rapper Snoop Dogg's real name is 'Cordozar Calvin Broadus, Jr.'.', correct_answer: 'True', …}

Return of questions[index].category: When I try to access any property it returns undefined.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You need to initialize the questions state to an empty array.

const [questions, setQuestions] = useState([]);

And when accessing the items you have to check whether the questions is populated by the API call.

{questions.length > 0 && questions[index].category}
about 4 years ago · Juan Pablo Isaza Relatório

0

Most likely your fetch is not being awaited properly. You need to wait for the json() as well. And remember setState is asynchronous and not immediate. Only on next rerender will you be sure to have data changed.

about 4 years ago · Juan Pablo Isaza Relatório

0

Maybe because you're initializing your questions state as an object so questions[1] is indeed undefined as soon as handleQuestions is resolved.

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