In today’s code-read, I learned a smart way to use a custom hook and generate objects from that. A brief background first about what we are trying to achieve. Let’s say we have an user
object and inside that object we have a property called attributions
This is an interesting property, it’s of type array and all the attributes of a user are coming as key-value pair. The user
object looks like below
Now let’s assume this user object is globally set (as it should be) and we want to show these attributes in different screens and components inside our app. There is also a catch here. The attributes inside the attributions object are not fixed. They may come there or not depending on the user. So we also need to handle this case. The below block of code is the interesting bit that I have learned today. Here it goes. The explanation is given inside the code comments.
Finally, we can just use the attributions hooks to get our desired info.
const { acceptanceRate, responseRate, responseTime } = useHostTrackedRate(info)
The full example is given in this snack.