Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember Data has duplicate records

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?

like image 752
Marc-François Avatar asked Feb 09 '15 19:02

Marc-François


2 Answers

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);
}
like image 158
Oren Hizkiya Avatar answered Nov 07 '22 03:11

Oren Hizkiya


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.

like image 44
Marc-François Avatar answered Nov 07 '22 04:11

Marc-François