react-store
react-store copied to clipboard
Allow for deep get/set based on . separated keys
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.
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
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!
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
Ahh, i read your updated article but didn't realize you created a new repo for it. Will check it out.