Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useEffect, useState } from 'react';
- function WebSocketDemo({token, getNotifications}) {
- const [messages, setMessages] = useState([]);
- const [ws, setWs] = useState(null);
- const [info, setInfo] = useState(null);
- useEffect(() => {
- // Create WebSocket connection.
- console.log("in websocket ", token)
- const socket = new WebSocket(`ws://localhost:8000/ws/notifications/?token=${token}`);
- // Connection opened
- socket.onopen = () => {
- console.log('WebSocket connected');
- console.log(token)
- // socket.send(JSON.stringify({ message: 'Hello server!' }));
- };
- // Listen for messages
- socket.onmessage = (event) => {
- const data = JSON.parse(event.data);
- if (data.message.role === "driver"){
- if (typeof getNotifications === "function") {
- // extract notification pk
- getNotifications(data.message.notification_pk);
- }
- }
- else if(data.message.role === "user") {
- if (typeof getNotifications === "function") {
- // extract notification pk
- getNotifications(data.message);
- }
- }
- };
- // Connection closed
- socket.onclose = (event) => {
- console.log('WebSocket disconnected:', event);
- };
- // Handle errors
- socket.onerror = (error) => {
- console.error('WebSocket error:', error);
- };
- setWs(socket);
- // Cleanup on component unmount
- return () => {
- socket.close();
- };
- }, []);
- const send_message = () => {
- ws.send(
- JSON.stringify({
- receiver_id: 37,
- message : info
- })
- )
- }
- return (
- null
- );
- }
- export default WebSocketDemo;
Advertisement
Add Comment
Please, Sign In to add comment