Home > Software engineering >  TypeError: data.map is not a function , how can i render data from the api to component
TypeError: data.map is not a function , how can i render data from the api to component

Time:08-08

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>
  );
}

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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[]);

  • Related