I was all smiles today š. Why? I naturally used some piece of code I had read about recently and it felt good. What was it? Optional chaining! I know Iām late to the party š, but letās get into it
In simple words, optional chaining prevents you from doing this:
resonse.data && response.data.animals && response.data.animals.cats && response.data.animals.cats.map(cat => {
// blah blah
})Do you see the ugliness in that? Yeah, guaranteed itās a bit exaggerated but you get the point.
Letās talk a look at how we can clean this up. First, letās have a look at a snippet of the response we are dealing with.
data: {
animals {
cats [
{
id: 0001,
name: "Fuzzy",
breed: "Bengal",
weight: 10,
age: 1,
}.
{
id: 0002,
name: "Tiger",
breed: "Abyssinian",
weight: 30,
age: 3,
},
{
....
}
],
dogs [
{
...
}
],
}
}Thankfully, we now have an optional chaining operator, ?. to the rescue! It has been promoted to Stage 4 by TC39. With optional chaining, all we have to do is:
response?.data?.animals?.cats.map(cat => {
// blah blah
})Pretty simple. No need to check to see if the nested properties exist before using them. Just use them - Well, you may need to pass it through babel. Read more about optional chaining and itās browser compatibility here
PS: You should not be dealing with such responses in 2020. Explore GraphQL to see how it can help get the right responses you need.