Added websocket

This commit is contained in:
Manik Maity
2024-11-13 18:37:05 +05:30
parent b3525c16dc
commit b394bbbd07
16 changed files with 308 additions and 48 deletions

View File

@@ -17,6 +17,7 @@
"react-query": "^3.39.3",
"react-router-dom": "^6.27.0",
"react-toastify": "^10.0.6",
"socket.io-client": "^4.8.1",
"zustand": "^5.0.1"
},
"devDependencies": {
@@ -1338,6 +1339,12 @@
"win32"
]
},
"node_modules/@socket.io/component-emitter": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz",
"integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==",
"license": "MIT"
},
"node_modules/@types/babel__core": {
"version": "7.20.5",
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
@@ -2183,7 +2190,6 @@
"version": "4.3.7",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz",
"integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"ms": "^2.1.3"
@@ -2303,6 +2309,28 @@
"dev": true,
"license": "MIT"
},
"node_modules/engine.io-client": {
"version": "6.6.2",
"resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.6.2.tgz",
"integrity": "sha512-TAr+NKeoVTjEVW8P3iHguO1LO6RlUz9O5Y8o7EY0fU+gY1NYqas7NN3slpFtbXEsLMHk0h90fJMfKjRkQ0qUIw==",
"license": "MIT",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.3.1",
"engine.io-parser": "~5.2.1",
"ws": "~8.17.1",
"xmlhttprequest-ssl": "~2.1.1"
}
},
"node_modules/engine.io-parser": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz",
"integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/es-abstract": {
"version": "1.23.3",
"resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.23.3.tgz",
@@ -4024,7 +4052,6 @@
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"dev": true,
"license": "MIT"
},
"node_modules/mz": {
@@ -5141,6 +5168,34 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/socket.io-client": {
"version": "4.8.1",
"resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.8.1.tgz",
"integrity": "sha512-hJVXfu3E28NmzGk8o1sHhN3om52tRvwYeidbj7xKy2eIIse5IoKX3USlS6Tqt3BHAtflLIkCQBkzVrEEfWUyYQ==",
"license": "MIT",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.3.2",
"engine.io-client": "~6.6.1",
"socket.io-parser": "~4.2.4"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/socket.io-parser": {
"version": "4.2.4",
"resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz",
"integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==",
"license": "MIT",
"dependencies": {
"@socket.io/component-emitter": "~3.1.0",
"debug": "~4.3.1"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -5947,6 +6002,35 @@
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"license": "ISC"
},
"node_modules/ws": {
"version": "8.17.1",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz",
"integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
},
"node_modules/xmlhttprequest-ssl": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.1.2.tgz",
"integrity": "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ==",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/yallist": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",

View File

@@ -19,6 +19,7 @@
"react-query": "^3.39.3",
"react-router-dom": "^6.27.0",
"react-toastify": "^10.0.6",
"socket.io-client": "^4.8.1",
"zustand": "^5.0.1"
},
"devDependencies": {

View File

@@ -1,4 +1,5 @@
import React from "react";
import { Link } from "react-router-dom";
const ErrorFallback = ({ onRetry }) => {
return (
@@ -14,6 +15,9 @@ const ErrorFallback = ({ onRetry }) => {
>
Retry
</button>
<Link to="/" className="btn btn-ghost w-full">
Go Home
</Link>
</div>
</div>
);

View File

@@ -5,6 +5,7 @@ import { useQuery, useQueryClient } from "react-query";
import ErrorFallback from "../components/Errors/ErrorFallback";
import useBookmark from "../hooks/useBookmark";
import { useNavigate } from "react-router-dom";
import { formatDataByDate } from "../utils/util";
function Bookmark() {
const { handleBookmark } = useBookmark();
@@ -34,6 +35,7 @@ function Bookmark() {
});
await handleBookmark(bookmarkId);
};
console.log(data);
return (
<div className="p-6 bg-base-200 h-screen">
@@ -58,7 +60,7 @@ function Bookmark() {
</tr>
</thead>
<tbody>
{data?.data?.map((bookmark, index) => (
{formatDataByDate(data.data).map((bookmark, index) => (
<tr key={bookmark._id}>
<th>{index + 1}</th>
<td className="text-white text-sm md:text-base">

View File

@@ -4,12 +4,14 @@ import { FaPlus, FaTrashAlt } from "react-icons/fa";
import { useMutation } from "react-query";
import createPollService from "../services/createPollService";
import { toast } from "react-toastify";
import { useNavigate } from "react-router-dom";
function CreatePollForm() {
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [options, setOptions] = useState([]);
const [optionInput, setOptionInput] = useState("");
const navigate = useNavigate();
const handleAddOption = () => {
if (optionInput.trim() == "") {
@@ -31,6 +33,7 @@ function CreatePollForm() {
const message = data?.message || "Poll created successfully";
toast.success(message);
handleClearPoll();
navigate(`/view/${data?.data?._id}`);
},
onError: (error) => {
console.log(error);

View File

@@ -8,6 +8,7 @@ import useLogout from "../hooks/useLogout";
import { useQuery } from "react-query";
import getUserPollData from "../services/getUserPollData";
import ErrorFallback from "../components/Errors/ErrorFallback";
import { formatDataByDate } from "../utils/util";
function Dashboard() {
const navigator = useNavigate();
@@ -23,7 +24,6 @@ function Dashboard() {
}
);
console.log(data);
const pollData = [
{
@@ -108,7 +108,7 @@ function Dashboard() {
</thead>
<tbody>
{data.map((poll, index) => (
{formatDataByDate(data)?.map((poll, index) => (
<PollTableRow key={poll._id} refetch={refetch} poll={poll} index={index} /> // Replace with actual path
))}
</tbody>

View File

@@ -1,38 +1,59 @@
import React, { useState } from 'react'
import { useQuery } from 'react-query'
import getPollsService from '../services/getPollsService'
import PollCard from '../components/PollCard/PollCard'
import ErrorFallback from '../components/Errors/ErrorFallback'
import React, { useState } from "react";
import { useQuery } from "react-query";
import getPollsService from "../services/getPollsService";
import PollCard from "../components/PollCard/PollCard";
import ErrorFallback from "../components/Errors/ErrorFallback";
function Polls() {
const [page, setPage] = useState(1);
const [limit, setLimit] = useState(6);
const {data, isLoading, isError, isSuccess, refetch} = useQuery(["polls", page, limit], () => getPollsService(page, limit), {
cacheTime: 1000 * 60 * 5, // 5 minutes
staleTime: 1000 * 60 * 10, // 10 minutes
})
const { data, isLoading, isError, isSuccess, refetch } = useQuery(
["polls", page, limit],
() => getPollsService(page, limit),
{
cacheTime: 1000 * 60 * 5,
staleTime: 1000 * 60 * 10,
}
);
return (
<div className="container mx-auto p-4 bg-base-200">
<h1 className="text-2xl font-bold text-center mb-6">Polls</h1>
{isSuccess && <div className="flex flex-wrap justify-center gap-6">
{data?.data?.polls?.map((poll) => (
<PollCard key={poll._id} poll={poll} />
))}
</div>}
{isLoading && <div className='flex flex-wrap justify-center gap-6 skeleton min-h-40'></div>}
{isError && <div className='flex justify-center gap-6'>
<ErrorFallback onRetry={() => refetch()} />
</div>}
<h1 className="text-2xl font-bold text-center mb-6">Polls</h1>
{isSuccess && (
<div className="flex flex-wrap justify-center gap-6">
{data?.data?.polls?.map((poll) => (
<PollCard key={poll._id} poll={poll} />
))}
</div>
)}
{isLoading && (
<div className="flex flex-wrap justify-center gap-6 skeleton min-h-40"></div>
)}
{isError && (
<div className="flex justify-center gap-6">
<ErrorFallback onRetry={() => refetch()} />
</div>
)}
<div className='flex justify-center gap-6 mt-6'>
<button className='btn btn-primary btn-circle' disabled={page <= 1} onClick={() => setPage(page - 1)}>Prev</button>
<button className='btn btn-primary btn-circle' disabled={data?.data?.totalPages === page} onClick={() => setPage(page + 1)}>Next</button>
<div className="flex justify-center gap-6 mt-6">
<button
className="btn btn-primary btn-circle"
disabled={page <= 1}
onClick={() => setPage(page - 1)}
>
Prev
</button>
<button
className="btn btn-primary btn-circle"
disabled={data?.data?.totalPages === page}
onClick={() => setPage(page + 1)}
>
Next
</button>
</div>
</div>
</div>
)
);
}
export default Polls
export default Polls;

View File

@@ -1,4 +1,4 @@
import React, { useState } from "react";
import React, { useEffect, useState } from "react";
import { Bar } from "react-chartjs-2";
import {
Chart as ChartJS,
@@ -15,30 +15,73 @@ import { FaBookmark } from "react-icons/fa";
import { toast } from "react-toastify";
import { makeChartDataObjFromPollData } from "../utils/util";
import useBookmark from "../hooks/useBookmark";
import { io } from "socket.io-client";
ChartJS.register(BarElement, CategoryScale, LinearScale);
function VotingPage() {
const { pollId } = useParams();
const [seletedOption, setSeletedOption] = useState(null);
const {handleBookmark} = useBookmark()
const [selectedOption, setSelectedOption] = useState(null);
const { handleBookmark } = useBookmark();
const [poll, setPoll] = useState(null);
const [socket, setSocket] = useState(null);
useEffect(() => {
const s = io("http://localhost:3000");
setSocket(s);
s.on("connect", () => {
console.log("Connected to the server");
s.emit("joinPoll", pollId);
});
return () => {
s.disconnect();
};
}, [pollId]);
const {
data: poll,
data,
isLoading,
isError,
refetch,
} = useQuery(["poll", pollId], () => getPollData(pollId), {
cacheTime: 10 * 100 * 60, // 10 minutes
staleTime: 20 * 100 * 60, // 20 minutes
cacheTime: 10 * 60 * 1000, // 10 minutes
staleTime: 20 * 60 * 1000, // 20 minutes
onSuccess: (data) => {
setPoll(data);
},
});
useEffect(() => {
if (socket) {
socket.on("pollDataUpdated", (data) => {
console.log("Received updated poll data:", data);
setPoll(data);
});
socket.on("error", (error) => {
console.error("Socket error:", error.message);
});
return () => {
socket.off("pollDataUpdated");
socket.off("error");
};
}
}, [socket]);
const mutation = useMutation(createVoteService, {
onSuccess: (data) => {
toast.success("Vote given successfully");
toast.success("Vote submitted successfully");
if (socket) {
socket.emit("vote", { pollId, success: data?.success });
}
},
onError: (error) => {
console.log(error);
console.error(error);
toast.error(
error?.response?.data?.message || "An unexpected error occurred"
);
@@ -46,6 +89,7 @@ function VotingPage() {
});
const handleOptionSelect = (id) => {
setSelectedOption(id);
mutation.mutate({ pollId, optionId: id });
};
@@ -61,6 +105,9 @@ function VotingPage() {
);
}
const chartData = makeChartDataObjFromPollData(poll);
return (
<div className="bg-base-200 min-h-screen p-6 text-white flex flex-col items-center">
<div className="w-full flex justify-between max-w-lg">
@@ -99,9 +146,9 @@ function VotingPage() {
onClick={() => handleOptionSelect(option._id)}
key={option._id}
className={`md:p-4 p-2 ${
seletedOption == option._id ? "bg-blue-500" : "bg-base-100"
selectedOption == option._id ? "bg-blue-500" : "bg-base-100"
} rounded-lg shadow-md flex items-center justify-center cursor-pointer ${
seletedOption == option._id ? "outline" : "hover:bg-base-300"
selectedOption == option._id ? "outline" : "hover:bg-base-300"
} transition`}
>
<span className="text-lg">{option.name}</span>

View File

@@ -19,4 +19,9 @@ export const makeChartDataObjFromPollData = (poll) => {
},
],
};
}
export const formatDataByDate = (data) => {
const fromatedData = data.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
return fromatedData;
}