how can I POST data using API from REACTJS

This is my react code here I want to POST Data using postPoll API and update polls state but I am not understand how can do that.

import React, { useState, useEffect } from "react";
import Poll from "react-polls";
import "../../styles.css";
import { isAutheticated } from "../../auth/helper/index";
import { getPolls, postPoll } from "../helper/coreapicalls";
import { useParams } from "react-router-dom";

const MainPoll = () => {
  const userId = isAutheticated() && isAutheticated().user._id;
  const pollId = useParams();
  const id = pollId._Id;
  console.log(id);
  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 = () => {
    postPoll();
    console.log("hello");
  };

  return (
    <div className="">
      <div className="container my-5">
        <h1 className="blog_heading my-3">Poll's of the Day</h1>
        <div className="row">
          {polls.reverse().map((poll, index) => (
            <div className="col-lg-4 col-12 poll_border" key={index}>
              <Poll
                noStorage
                question={poll.question}
                answers={Object.keys(poll.options).map((key) => {
                  return {
                    option: key,
                    votes: poll.options[key].length,
                  };
                })}
                onVote={handalchange}
                className="mb-2"
              />
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export default MainPoll;

this is my frontend-enter image description here
and here is my backend API –

// post
export const postPoll = (pollId, post) => {
  return fetch(`${API}/vote/${pollId}`, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(post),
  })
    .then((response) => {
      return response.json();
    })
    .catch((err) => console.log(err));
};

13 thoughts on “how can I POST data using API from REACTJS”

Leave a Comment