I'm working on e-commerce react website.I'm facing the issue to create react order notification popup,when we recieve new order in database.please help and guide me how can i build this functionality.i have try socket.io also.but im not able to solve it.
CodePudding user response:
With socket io you can use rooms:
Server side, on connection you let the user join the room with his userId.
//client side
var socket = io.connect(window.location.origin,{query:'userId=1'});
or better you can user a token:
//client side
var socket = io.connect(window.location.origin,{query:'token=YOURTOKEN'});
Then you can join room on connection:
// server side
io.socket.on('connection', function (socket) {
let token = socket.handshake.query.token;
userId = getUserByToken(token); // set directly userId or find your userid by token, jwt for example
socket.join("user-" userId);
});
Now, when you receive an order you need to emit the message to a specific room
socket.to("userID").emit("notification", "your message");
In you frontend you need to listen to notification:
socket.on("notification", (...args) => {
// print your message
});
CodePudding user response:
Below is the I would approach for real-time update on the Admin dashboard when an order is placed.
- Setup Socket.IO on both Backend and Frontend
- On the frontend listen to specific channel like new-order and from the server send data of new order on new-order channel
- On the frontend when you get event for new-order show the notification to the ADMIN
Below is the implementation of the backend for Socket.io where you are facing difficulty
SocketController.ts
import {Server,ClientSocket} from 'socket.io';
import {Container} from "typedi";
import socketioJwt from 'socketio-jwt';
export default class SocketController {
constructor() {
.sockets
.on('connection',socketioJwt.authorize({
secret: Container.get('jwt_secret'),
decodedPropertyName: 'user',
timeout:3000,
}))
.on('authenticated',(socket)=>{
socket.on('disconnect', () => {
delete Container.get('s-users')[socket.user.id];
})
Container.get('s-users')[socket.user.id] = {socketId:socket.id,userId:socket.user.id};
})
}
}
App.ts
import 'dotenv/config';
import 'reflect-metadata';
import bodyParser from 'body-parser';
import express from 'express';
import SocketController from "./SocketController";
export const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
new SocketController();
server.listen(port, () => {
console.log(`Express Server running on port ${port}`);
});
The above is the approach you can implement Socket.io in the backend, you can skip JWT for now, as you application start working you can add JWT.