0

I am deleting a Realm db Object, but I want to access its value after deleting so that I can use it in other processings. This is how my code looks like:

const theObject = realm.objects('Products').filtered("_id == $0", "61bba17fc7e82eaae53527de")

//the fetched theObject(response) looks like this: 
[{_id:'61bba17fc7e82eaae53527de', name: 'Sugar'}]

var productName = theObject[0].name

realm.write(() => {

 realm.delete(theObject)

})

return productName //I want to use this productName here to do some other stuffs

I want to use/return the productName for doing some other things, but when i try to access it, i find it undefined or null.

I think this is caused because the theObject has been deleted and hence the productId can't be acceced, but I wonder why it is that way since i already caught that id initially when I assigned it before deleting. ie productName = theObject[0].name

Now,My question is, How can I still get/access/return that productName?

Amani
  • 227
  • 1
  • 10
  • You can't delete objects in JS, only Garbage Collector can do that. You have only deleted a reference to an object (a property) from `realm`. – Teemu Dec 19 '21 at 14:31
  • @Teemu Now after deleting that reference to an object, How can I access that *productName*? What should be the solution to my problem? – Amani Dec 19 '21 at 14:44
  • 1
    If you run your code, `productName` still contains what was assigned to it. – Teemu Dec 19 '21 at 14:48
  • 1
    @Teemu SOLVED. The productName was returning an array of one object ie [{}], so I solved it by accesing that object and finding the value – Amani Dec 19 '21 at 16:04

1 Answers1

0

This shouldn't be possible. Comment out the delete, and console log productName to ensure things are behaving as you think they are.

Also it looks like your missing a var/let/const for productName

const productName = theObject[0].name

Edit:

Since these are async operations its possible that real.objects('Prodcuts') is losing the race to realm.delete(). You can solve this by awaiting your access request before attempting to deleting.

Spankied
  • 1,626
  • 13
  • 21
  • I should not comment out the delete because I WANT THAT DOC TO BE DELETED. The issue here is, I fetch the Object and get its value for other uses(the returned productName) and then I delete the Object. How can I do this? – Amani Dec 19 '21 at 14:48
  • 1
    Of course YOU WANT THE DOC TO BE DELETED. But for testing purposes, you should comment it out to ensure you're able to fetch the product in the first place. – Spankied Dec 19 '21 at 14:53
  • I SOLVED IT, The productName was returning an array of one object ie [{}], so I solved it by accesing that object and finding the value – Amani Dec 19 '21 at 16:04