The react native documentation for AsyncStorage.mergeItem() is a bit vague and provides no example how it works or how it’s used. Today, I figured it out.
Here’s their current description
Merges existing value with input value, assuming they are stringified json. Returns a
Promise
object. Not supported by all native implementations.
If you’re familiar with the Object.assign(), this is similar except it does a deep merge. Let me explain with an example.
let KEY1 = 'test_merge' let KEY2 = 'test_assign' // I'll use this in the next example let ORIG = { 'simple_value': 1, 'dual_obj': { 'dual_obj_1': 1, 'dual_obj_2': 1 }, 'single_obj': {'single_obj_1': 1} } let DELTA = { 'dual_obj': { 'dual_obj_1': 2, 'dual_obj_new': 2 }, 'simple_value': 2, } AsyncStorage.setItem(KEY1, JSON.stringify(ORIG), () => { AsyncStorage.mergeItem(KEY1, JSON.stringify(DELTA), () => { AsyncStorage.getItem(KEY1, (err, result) => { console.log('KEY1 result of merged object: %O', JSON.parse(result)) }) }) })
I’ve created two objects ORIG
and DELTA
. After setting the first item in local storage using AsyncStorage.setItem()
, I then merge the DELTA
object in. And here’s the result..
Notice that in “dual_obj” we’ve succeeded in modifying the “dual_obj_1” value. As well, we were able to add the “dual_obj_new” key. We also updated the “simple_value”. That’s a deep merge.
I thought I’d get the same thing if I were to do an Object.assign(ORIG, DELTA)
, but I was wrong. I used KEY2 with the following code…
AsyncStorage.setItem(KEY2, JSON.stringify(ORIG), () => { AsyncStorage.setItem(KEY2, JSON.stringify(Object.assign(ORIG,DELTA)), () => { AsyncStorage.getItem(KEY2, (err, result) => { console.log('KEY2 result of assigned object: %O', JSON.parse(result)) }) }) })
And ended up with the following output…
Notice the missing object.
If you found this helpful, give me a shout out on twitter (@geirmanc)
> is displaying instead of > on this page http://www.geirman.com/2016/03/react-natives-asyncstorage-mergeitem/
Recent Posts
Recent Comments
Archives
Categories
Meta