'How to listen for event in callback function with socket.io?
I have a simple socket and firebase API. When a value in my Firebase database changes, I want to emit an event from my socket server.
So far I have something like:
io.on("connection", (socket) => {
socket.on('resource', ({ resourceId }) => {
const ref = db.ref(`resources/${resourceId}`);
ref.on('child_changed', (snapshot) => {
const resource = snapshot.val()
socket.emit(resource)
})
})
});
However, my child_changed callback doesn't seem to get called here because I guess the listener gets destroyed after the socket.on event has finished?
In psuedo code, I want to do something like this:
// add some form of listener for resource id
addListnerSomehow();
// create firebase ref for that resourceId
const ref = db.ref(`resources/${resourceId}`);
// emit new value via socket when resource value changes
ref.on('child_changed', (snapshot) => {
const resource = snapshot.val()
socket.emit(resource)
})
How can I emit an event to specific listeners inside a callback like this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
