diff --git a/client/src/components/Poll/index.jsx b/client/src/components/Poll/index.jsx index f4ea25e..2ee833b 100644 --- a/client/src/components/Poll/index.jsx +++ b/client/src/components/Poll/index.jsx @@ -6,19 +6,30 @@ import { CREATE_VOTE } from "../../utils/mutations"; import Auth from "../../utils/auth"; const Poll = ({ poll }) => { + const [voteFeedback, setVoteFeedback] = useState(''); const [createVote, { error, data }] = useMutation(CREATE_VOTE); - const currentUserId = Auth.getProfile().authenticatedPerson._id; + + let hasUserVoted = false; + if (Auth.loggedIn()) { + const currentUserId = Auth.getProfile().authenticatedPerson._id; - const hasUserVoted = poll.votes.some( - (vote) => vote.user._id === currentUserId - ); - console.log(hasUserVoted, poll.header); - console.log(poll); + hasUserVoted = poll.votes.some( + (vote) => vote.user._id === currentUserId + ); + + //console.log(hasUserVoted, poll.header); + //console.log(poll); + } + + const handleChoiceClick = async (choiceId) => { if (!poll || !poll._id) { console.error("Poll or poll ID is undefined"); return; + } else if (hasUserVoted) { + setVoteFeedback('Already Voted'); + return; } console.log("Choice Id:", choiceId); @@ -27,11 +38,18 @@ const Poll = ({ poll }) => { const { data } = await createVote({ variables: { pollId: poll._id, choiceId: choiceId }, }); + + window.location.reload(); } catch (error) { console.error("error:", error); } }; + //Prompts user to login to vote + const ifLoggedOut = () => { + setVoteFeedback('Please login to vote'); + } + return (
@@ -43,11 +61,12 @@ const Poll = ({ poll }) => { className="pollChoice" id={choice._id} key={index} - onClick={hasUserVoted ? null : () => handleChoiceClick(choice._id)} + onClick={Auth.loggedIn() ? () => handleChoiceClick(choice._id) : ifLoggedOut} > {choice.text}

))} +

{voteFeedback}

Created by: {poll.creator.username}

);