Pick Helper

The pick helper is a quick way to read object key values at any level without sacrificing readability and reactivity of state.

The problem

If you have a state value and try to read a deep value it would look like so:

const [user, setUser] = state({name: "John Doe"})

html`${() => user().name}`

The issue here is that when the user changes the DOM will not update because the template only react to states that are provided directly in the template. The above example a function is provided and the template cannot see inside the function to see the state and subscribe to changes.

Instead, you can use the pick helper which lets you provide the object and the keychain to look for

const [user, setUser] = state({name: "John Doe"})

html`${pick(user, 'name')}`

The template in this case sees the state because the helper will tell the template about it and therefore update when the state changes.

It takes two arguments and both are required.

pick(OBJECT, KEYCHAIN_STRING)

  • OBJECT: Any JavaScript object which value can be chained to access the value (Array, Object).
  • KEYCHAIN_STRING: A string with dot separated keys.

Deep values

It would not be fair if the key access was shallow. The problem would persist for access of deep values.

The pick helper second argument can be a dot-notation string that can go deep.

html`${pick(user, 'role.name')}`

html`${pick(list, '1.status.value')}`

html`${pick(response, 'projects.0.name')}`

You may also use it to access other keys from the object, for example the length or size.

html`${pick(list, 'length')}`

html`${pick(set, 'size')}`