I am using the api with difference event channelName1
and channelName2
//...this the realtime record
socket.on(channelName1, message => {
console.log(channelName1, message1);
//this return single item list in realtime`[{"price":100,"size":0.001}]`
});
//realtime snapshot collection of records
socket.on(channelName2, message => {
console.log(channelName2, message2);
//this return the collection `[{"price":100,"size":0.01}, {"price":200,"size":0.02} ]`
$('#live').text(message2)
});
I want to want to update size of message2
if I found the price":100
is present in the collection message2
, so the after update message2 will
[{"price":100,"size":0.001}, {"price":200,"size":0.002} ]
anyone could you guide me how I can do this update from channelName1 to ChannelName2 data?
You have to store the single items somewhere and when the collection arrives you need to:
I have also included a record in the collection that cannot be found so you can see what happens there: it remains unchanged.
Ignore the small changes I made to simulate the sockets. Hopefully you can see the big picture of what I'm doing.
Hope this helps and happy coding.
// Stores each single item that arrives.
let singleItems = [];
// ...this is the realtime record.
function socketOn1(channelName1, message1) {
console.log(channelName1, message1);
// Store each single item as it arrives.
singleItems.push(message1[0]);
};
// realtime snapshot collection of records
function socketOn2(channelName2, message2) {
console.log(channelName2, message2);
// For each element in the collection, find
// the same record in the single items and
// if found, update the price.
results = message2.map((elem) => {
found = singleItems.find(
(single) => single.price === elem.price
)
if (found) {
elem.size = found.size
}
return elem
})
console.log('results:')
console.log(results)
};
// This stuff just simulates stuff arriving to sockets.
// You can ignore it if you want. But look at the order
// in which they are called.
let singleItemsMock = [{
"price": 100,
"size": 0.01
},
{
"price": 50,
"size": 0.02
},
{
"price": 25,
"size": 0.03
},
{
"price": 10,
"size": 0.04
}
]
let collectionMock = [{
"price": 100,
"size": 0.001
},
{
"price": 50,
"size": 0.002
},
{
"price": 13,
"size": 0.005
}
]
socketOn1(null, [singleItemsMock[0]])
socketOn1(null, [singleItemsMock[1]])
socketOn1(null, [singleItemsMock[2]])
socketOn1(null, [singleItemsMock[3]])
socketOn2(null, collectionMock)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With