0.4.1 • Published 3 years ago

safe-touch v0.4.1

Weekly downloads
4
License
MIT
Repository
github
Last release
3 years ago

Safe Touch

Retrieving deeply buried properties is a common problem in JavaScript, it could crash your application if you try to access a property that doesn't exist.

const state = { user: { name: "EnixCoda" } };
console.log(state.user.name); // 'EnixCoda'
state.user = null;            // simulating logout
console.log(state.user.name); // Uncaught TypeError: Cannot read property 'name' of null

Safe touch is a safe way to access deeply buried properties.

const $state = safeTouch(state);  // retrieving properties from $state is always safe
console.log($state() === state);  // true; invoke to get the original value
let { user: { name } } = $state;  // support native destructuring
console.log(name());              // 'EnixCoda'
console.log($state.user.name());  // 'EnixCoda'

state.user = null;                // simulating logout
let { user: { name } } = $state;  // support native destructuring
console.log(name());              // undefined; no errors!
console.log($state.user.name());  // undefined; no errors!

Playground

Available as safe-touch on npm.

> yarn add safe-touch

Why choose Safe Touch?

  • state && state.user && state.user.name is verbose.
  • wrapping with try ... catch is verbose and creates new code block.
  • lodash _.get has no TypeScript support.
0.4.1

3 years ago

0.4.0

3 years ago

0.3.0

4 years ago

0.2.6

4 years ago

0.3.1

4 years ago

0.2.5

5 years ago

0.2.4

5 years ago

0.2.3

5 years ago

0.2.2

5 years ago

0.2.1

5 years ago

0.2.0

5 years ago

0.1.2

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago