In my app, a user can create a message and send it. When the user sends the message, the message is created with createRecord
and the server replies with 201 Created if successful.
Also, the user can get messages from other users through a websocket. When it receives a message, I push it into the store with pushPayload
.
var parsedData = JSON.parse(data);
this.store.pushPayload('message', parsedData);
The problem is, when a user sends a message and saves it, they also get it back from the websocket, and even though both objects have the same id, the store ends up with duplicate messages.
How can I tell the store than when I push or save something with the same id of an already existing element, it should override it?
Simply perform a check to see whether the model is already in the store before adding it:
var parsedData = JSON.parse(data);
if(this.store.hasRecordForId ('typeOfYourRecord', parsedData.id)){
// logic you want to run when the model is already in the store
var existingItem = this.store.find('typeOfYourRecord', parsedData.id);
// perform updates using returned data here
} else {
this.store.pushPayload('message', parsedData);
}
The only method I found to avoid this problem is to run my update in a new runloop. If the delay in ms in long enough, the problem won't occur.
It seems that receiving the update from the websocket and the request at nearly the same time creates a race condition in Ember Data.
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