Rushabh Rakholiya
Rushabh Rakholiya

Reputation: 415

Realm : delete specific object

I'm developing app using react native where i need to delete specific objects which give me in filtered method but it gave me error called

"Can only delete objects within a transaction."

Here is my Code

allObj1 = {
                id : 1,
                speed : "1",
                accuracy: "100",
                bearing: "1",
                longitude: "192",
                altitude: "1111",
                latitude: "1111",
                time: "11111",
                locationProvider: "2222",
            };

        allObj2 = {
                id : 2,
                speed : "1",
                accuracy: "100",
                bearing: "1",
                longitude: "192",
                altitude: "1111",
                latitude: "1111",
                time: "22222",
                locationProvider: "2222",
            };

        allObj3 = {
                id : 3,
                speed : "1",
                accuracy: "100",
                bearing: "1",
                longitude: "192",
                altitude: "1111",
                latitude: "1111",
                time: "333333",
                locationProvider: "2222",
            };

        realm.write(() => {
            realm.create('Location',allObj1 );          
            //realm.delete(firstObj);
            realm.create('Location',allObj2 );
            realm.create('Location',allObj3 );
        });         

        let locationO = realm.objects('Location');
        //let tanlocation = locationO.filtered('id >1 AND id <3 ');
        // Observe Collection Notifications         

        realm.objects('Location').filtered('id >=1 AND id <=3').addListener((tanlocation, changes) => {

            try{
                tanlocation.forEach((realmObj,index) => {                           
                    realm.delete(realmObj);             
                });
            }
            catch(err){
                console.log(err);
            }
        });


        // Unregister all listeners
        realm.removeAllListeners();

        //realm.delete(tanlocation);
        //console.log( tanlocation );

        console.log(locationO);

It throw me error called "Can only delete objects within a transaction."

anyone has faced this kind of issue? anybody knows how to fixed this or alternative method to achieved mentioned functionality

Upvotes: 12

Views: 11964

Answers (2)

Malhar Bhutto
Malhar Bhutto

Reputation: 51

You can delete specific user using the following code.

realm.write(() =>
  realm.delete(
    realm.objects('user').filter(userObj => userObj.id == id),
  ),
);

Upvotes: 5

Chris Dolphin
Chris Dolphin

Reputation: 1598

Gotta wrap the delete in a realm.write, like you do with realm.create.

realm.write(() => {
    realm.delete(realmObj)
})

This worked for me when I ran into this issue. Only realized once I read this Github comment

Upvotes: 16

Related Questions