Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

node.js - fetching data from API in react poll

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
  const handalchange = () => {
    console.log("hello");
  };

  return (
    <div className="">
      <div className="container">
        <h1 className="blog_heading">Poll's of the Day</h1>
        <div className="row">
          {polls.map((poll, index) => (
            <div className="col-lg-4 col-12" key={index}>
              <Poll
                question={poll.question}
                answers={poll.options.none}
                onVote={handalchange}
              />
            </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/65936091/fetching-data-from-api-in-react-poll

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

1 Answer

0 votes
by (71.8m points)

There is two little mistakes in the code that you show us:

  1. the first One you imported import Polls from "./polls"; and you call <Poll noStorage question={poll.question} answers={poll.options} onVote={handleVote}/> just change Poll by Polls.
  2. const [pollAnswers, setPollAnswers] = useState([...answers]); this didn't work because you need to pass a initial value for your state and answer is not yet initialize and accessible. just change useState([...answers]); by useState([]);
    UPDATE:
    you need to pass an array to answers props . We can see in your console screenshot that the array of options has "none" as key so try this : <Poll noStorage question={poll.question} answers={poll.options.none} onVote={handleVote}/> ("none" is a strange key...)
    UPDATE
    Your data object is not well formated to fit react-polls answers props. in the npmjs doc of react-polls we can see an example of options and it's an array of object like this:
[
  { option: 'Yes', votes: 8 },
  { option: 'No', votes: 2 }
]

so based on the data console log that you add in your question it should looks like this:

[
  {
    createdAt: "2020-12-01T21:43:23:21.061Z",
    options: {
      none: [ { option: 'Yes', votes: 8 },
      { option: 'No', votes: 2 }],
      student: ["12345678978945"],
      teacher: ["7894567894231"]
    },
    question: "Are you student ot teacher",
    updatedAt: "2020-12-01T21:43:23:21.061Z"
  }
]

see a sandBox here working with your code (except getPolls()). I think the issue come from the API.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...