Simple and natural nested property accessor.
Protect yourself from "Cannot read property 'x' of undefined" runtime exception.
Package is available in npm. It's in umd format so it will work correctly with all popular bundlers(webpack) and also nodejs.
npm install guardy --save
Using yarn
yarn add guardy --save
For direct usage without bundler, use iife format and import file directly:
<script src="dist/guardy-iife.min.js"></script>
Wrap object with guardy and then access with no stress any property at any nested level. If not defined it will fallback to empty object {} instead of throwing "Cannot read property 'x' of undefined" runtime exception.
import { guardy } from "guardy";
var nestedProp = guardy(myObj).I.can.safely.access.any.property;
With defined fallback value
import { guardyFb } from "guardy";
var nestedProp = guardyFb(myObj, "myFallBackStringOrAnyType").I.can.safely.access.any.property.__value__;
Guardy can be successfully used together with redux when trying to access not yet initialized state properties by providing safe fallback values.
const mapStateToProps = ({ NestedReducerState }) => (
{
var nestedStateObject = guardy(NestedReducerState).a.nested.object;
var nestedStateString = guardyWithFallback(NestedReducerState, "defaultString").a.nested.string.__value__;
return {
nestedStateObject,
nestedStateString
}
}
);
- nodejs >= 6.4.0
- browser with Proxy compatibility, see https://caniuse.com/#search=Proxy
The code in this project is licensed under MIT license.