pth - What
This is a simple helper for selectors in a React Redux environment. It simplifies the act of creating a function that pics out certain parts of your state depending on the arguments passed in.
At its simplest, you can compare these two functions:
// raw jsconst getNameById = { const user = stateusersid return user && username} // pthconst getNameById =
So pth
returns a function that takes an arbitrary number of arguments and
attempts to access the property you are looking for. If it fails, it returns
undefined
.
Of course you can also use it to create small utility functions for accessing properties on objects:
const getFirstName = const getLastName = // etc...
options argument
pth
also takes an options
object as second parameter, where you can change
a few things:
// If name isn't found, return 'Mr Nobody'const getNameById = // Change the identifier from $ to %const getNameById = // Change the splitter from . to ->const getNameById =
pth.fromObject
There is a second version where the returned function only takes two arguments:
- the object where we expect to find the data we are looking for, and
- an object with the keys we need
The path string we pass to it also looks a little different (better if you ask me).
These two are equevalent:
// raw jsconst getNameById = { const user = stateusersid return user && username} // pthconst getNameById = pth
This version takes the same options
object as second parameter as the above.
Because too much magic?
If giving pth
a string is too much magic for you, then know that it also
takes an array.
const getNameById = const getNameById = pth
Tiny caution
I don't recommend "building" the function every time you call it. That is, this is probably not a great idea:
const getName = user
The reason is performance. It's not that it is particularly slow; but it is splitting up a string and looping through each of the sections every time; so really it's better to just build the function ahead of time.