react-store icon indicating copy to clipboard operation
react-store copied to clipboard

Allow for deep get/set based on . separated keys

Open nab911 opened this issue 5 years ago • 4 comments

Often times I want to update a property a few levels down an object. Instead of having to pull the object from the store, update the key, and set it back to the store, we could allow for parsing of the passed in key to deep get/set a property.

Example:

store.set('map', { 
  level1: { 
    level2: {
      thing: 1
    }
  }
});

const thing = store.get('map.level1.level2.thing'); // thing === 1 

Same idea for a deep set. Unless there is some philosophical reason for keeping store access single level, this could be a nice enhancement.

nab911 avatar Jan 10 '20 22:01 nab911

Thew store is a key/value map, so you should create another function like store.getNestedProperty('map.level1.level2.thing') because if you use store.get('map.level1.level2.thing') the store lloks for a map.level1.level2.thing property.

A solution could be to use destructuring, like this

const {level1 : {level2 : {thing} }} = store.get('map');

however this could cause TypeError if some of the object struvture is missing and you should assign default values, like this

const {level1 = {} : {level2 = {}: {thing} }} = store.get('map');

but this is not really readable.

Another solution is writing a custom function that extracts the nested properties

function getNestedProperty(property) {
 const propertiesPaths property.split['.'];
 let rootObject = store.get(propertiesPaths.pop());
 while(propertiesPaths.length>0){
   rootObject = rootObject[propertiesPaths.pop()];
 }
return rootObject;
}

This code is just an idea, you should add proper checks to avoid infinite loops and type errors if some nested properties are missing or undefined

Spyna avatar Jan 13 '20 13:01 Spyna

Yeah, that was the reason I opened the issue, to get your opinion on it. I have no problem creating a fork with the new functionality and issuing a PR.

As for creating the new function, while it is a breaking change to parse strings like map.level1.level2.thing, it is bad practice to be using . periods in key names any ways.

I'm going to create a fork and update/add the functionality I need. Will issue a PR and get your thoughts on it. Great job on the repo!

nab911 avatar Jan 13 '20 14:01 nab911

Thanks, just keep in mind that someone could use the . to separate logically the domains on the app, for example: login.date and post.date.
PRs on this project are welcome, but there's also a version of this lib with react hooks, which is newer. It offers almost the same API: https://github.com/Spyna/react-context-hook

Spyna avatar Jan 13 '20 15:01 Spyna

Ahh, i read your updated article but didn't realize you created a new repo for it. Will check it out.

nab911 avatar Jan 13 '20 15:01 nab911