Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

164
Vistas
TypeError: data.map is not a function , how can i render data from the api to component

whenever I try to display data from the API by using .map this error happens.

the data part I want to access from the API is an array. if it's not an array is there a way that can I change it into an array of objects? and here is my app.js

import React from "react";
import { useState } from "react";

export default function App() {
  const [data, setData] = useState([]);

  async function fetchData() {
    const response = await fetch(
      "https://opentdb.com/api.php?amount=5&type=multiple"
    );
    const data = await response.json();
    const [item] = data.results;
    setData(item);
  }

 

  return (
    <div className="app">
      <h1>question generate </h1>
      <button onClick={fetchData}>new question</button>

      {data &&
        data.map((quiz, index) => {
          return (
            <div className="queations">
              <p>{quiz.question}</p>
              <button onClick={boo} key={index}>
                {quiz.correct_answer}
              </button>
              <button>{quiz.incorrect_answers}</button>
              <button>{quiz.incorrect_answers}</button>
              <button>{quiz.incorrect_answers}</button>
            </div>
          );
        })}
    </div>
  );
}

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

const [item] = data.results; line causing error as it saving only first object into the state. So just replace by const item = data.results;

about 4 years ago · Juan Pablo Isaza Denunciar

0

You should declare an interface first:

interface Data {
  question: string;
  correct_answer: string;
  // ...

And then use it to type the state:

const [data, setData] = useState<Data[]>([]);

After this everything should work fine

about 4 years ago · Juan Pablo Isaza Denunciar

0

this code const [item] = data.results; create item variable (first element of the array), you need to create interface


    interface Data {
      question: string;
      correct_answer: string;
      incorrect_answers: string[];
    }

and store results directly into the state setData(data.results as Data[]);

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda