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
174 views
in Technique[技术] by (71.8m points)

node.js - how to create poll using API with react functional component

this is my react js code and I want to connect with my node js API but I don't understand how to that ...!

import React, { useState } from "react";
import Poll from "react-polls";
// import "./styles.css";

/**
 * https://stackoverflow.com/questions/65896319/react-js-class-poll-convert-into-react-hooks-poll
 */

// Declaring poll question and answers
const pollQuestion = "Youtube is the best place to learn ?";
const answers = [
  { option: "Yes", votes: 7 },
  { option: "No", votes: 2 },
  { option: "don't know", votes: 1 },
];

const Fakepolls = () => {
  // Setting answers to state to reload the component with each vote
  const [pollAnswers, setPollAnswers] = useState([...answers]);

  // Handling user vote
  // Increments the votes count of answer when the user votes
  const handleVote = (voteAnswer) => {
    setPollAnswers((pollAnswers) =>
      pollAnswers.map((answer) =>
        answer.option === voteAnswer
          ? {
              ...answer,
              votes: answer.votes + 1,
            }
          : answer
      )
    );
  };

  return (
    <div>
      <Poll
        noStorage
        question={pollQuestion}
        answers={pollAnswers}
        onVote={handleVote}
      />
    </div>
  );
};

export default function App() {
  return (
    <div className="App">
      <Fakepolls />
    </div>
  );
}

It work's fine with

// Declaring poll question and answers
    const pollQuestion = "Youtube is the best place to learn ?";
    const answers = [
      { option: "Yes", votes: 7 },
      { option: "No", votes: 2 },
      { option: "don't know", votes: 1 },
    ];

but I want to connect this poll with my API instead of Declaring it ..! this is my api- to get data -> ( router.get("/poll/:pollId", getPoll); //)

exports.getPoll = async (req, res, next) => {
  try {
    const { pollId } = req.params;
    const polls = await Poll.findById(pollId);
    if (!polls) throw new Error("no polls found");
    res.status(200).json(polls);
  } catch (error) {
    error.status = 400;
    next(error);
  }
};

This is a postman image - enter image description here

and this API for POST data- and my node js code -

     exports.votes = async (req, res, next) => {
  try {
    /**
     * 1. get the poll from db
     * 2. check if the user already exists in any option
     * 3. if user has already selected any option do nothing
     * 4. if user has selected any other option remove from that option
     * 5. if user does not exist in any option, insert his user id to selected option
     */
    const { pollId } = req.params;
    let { userId, answer } = req.body;
    // get selected poll from db
    const poll = await Poll.findById(pollId);
    if (answer && poll) {
      answer = answer.toLowerCase();
      ///Finf the Poll

      let existingVote = null;
      Object.keys(poll.options).forEach((option) => {
        // loop on all options, check if the user already exists in any option
        if (poll.options[option].includes(userId)) {
          existingVote = option;
        }
      });
      if (existingVote == null) {
        // if there is no existing vote save it to db
        try {
          const push = {};
          push[`options.${answer}`] = userId;
          const update = await Poll.findByIdAndUpdate(
            pollId,
            { $push: push },
            { upsert: true }
          );
          res.status(201).json(update);
        } catch (err) {
          error.status = 400;
          next(error);
        }
      } else if (existingVote && existingVote.length > 0) {
        // check if answer is same as previous, if yes send not modified
        if (existingVote.toLowerCase() === answer.toLowerCase()) {
          res.status(304).send("Response already saved");
        } else {
          // delete the previous response and save it in new
          if (
            Array.isArray(poll.options[existingVote]) &&
            poll.options[existingVote].length > 0
          ) {
            // TODO: filtering this is not returning array but 1
            poll.options[existingVote] = poll.options[existingVote].filter(
              (vote) => vote != userId
            );
            poll.options[answer] = poll.options[answer].push(userId);
            const update = await Poll.findByIdAndUpdate(pollId, {
              $set: { options: poll.options },
            });
            res.status(201).json(update);
          }
        }
      } else {
        error = {
          status: 500,
          message: "Something went wrong",
        };
        next(error);
      }
    } else {
      error = {
        status: 404,
        message: "Poll not found",
      };
      next(error);
    }
  } catch (error) {
    error.status = 400;
    next(error);
  }
};

this is a POSTMAN image using POST to store data --- > enter image description here

how can I connect API with react poll

question from:https://stackoverflow.com/questions/65899934/how-to-create-poll-using-api-with-react-functional-component

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

1 Answer

0 votes
by (71.8m points)
Waitting for answers

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

...