I want to implement a simple notification system. When user1
likes user2
's post, user2
should get a real-time notification from user1
.
Here is a part of the client function (Redux action) where someone likes a post:
.then(() => {
const socket = require("socket.io-client")(
"http://localhost:5000"
);
socket.emit("like", user, post);
});
Here is the server socket function where a notification is created after user1
likes user2
's post:
io.on("connection", (socket) => {
socket.on("like", async (user, post) => {
if (!post.post.likedBy.includes(user.user._id)) {
const Notification = require("./models/Notification");
let newNotification = new Notification({
notification: `${user.user.username} liked your post!`,
sender: user.user._id,
recipient: post.post.by._id,
read: false,
});
await newNotification.save();
io.emit("notification");
}
});
});
Here is the client function after the notification is created:
socket.on("notification", () => {
console.log("liked");
});
Now the problem with this is the console.log('liked')
appears for both user1
and user2
. How can I emit to only that user that receives the notification? How can socket.io find this specific user2
that receives the notification from user1
?
recipient
to receive a notification.