Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

javascript - show api data to frontend(poll) using reactjs

I want to fetch data from API and show frontend using react but I am getting error from frontend side which is (TypeError: answers.map is not a function ) so how can I solve this error --

MY CODE IS -

import React, { useState, useEffect } from "react";
import Poll from "react-polls";
import { getPolls } from "../helper/coreapicalls";

const MainPoll = () => {
  const [polls, setPoll] = useState([]);
  const [error, seterror] = useState(false);
  // Setting answers to state to reload the component with each vote
  const [pollAnswers, setPollAnswers] = useState([]);

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

  const loadPoll = () => {
    getPolls().then((data) => {
      if (data.error) {
        seterror(data.error);
      } else {
        setPoll(data);
        console.log(data);
      }
    });
  };

  // Handling user vote
  // Increments the votes count of answer when the user votes

  return (
    <div className="">
      <div className="container">
        <h1 className="blog_heading">Poll's of the Day</h1>
        <div className="row">
          {polls.reverse().map((poll, index) => (
            <div className="col-lg-4 col-12" key={index}>
              <Poll question={poll.question} answers={poll.options} />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default MainPoll;

Data which I am getting from API is- enter image description here

Here I have Question , 3 options how can I show to frontend

Error -enter image description here

question from:https://stackoverflow.com/questions/65952560/show-api-data-to-frontendpoll-using-reactjs

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is:

field options from the API is an object as I see.

But Poll component trying to interact with it like it is an Array: answers.map(answer => answer.option)

As I see from the doc, data format should be:

[
  { option: 'Yes', votes: 8 },
  { option: 'No', votes: 2 }
]

UPDATE: you can use a similar snippet to transform your data into the required format.

data.map(answer => {
  return {
    question: answer.question,
    answers: Object.keys(answer.options).map(key => {return {option: key, votes: 0}})
  }
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...