React encourages you to write declarative code. Every now and then you end up writing code that looks like this:
payload && payload.data && payload.data.items && payload.data.items && ( /*.. whatever .. */ )
It is a bummer to even write smaller expressions such as
onClose && onClose();
Now for CRA based apps, you can use the new optional chaining feature. First, you must upgrade to version 3.3.0. If applicable, you may also need to upgrade your TypeScript to 3.7+ and probably upgrade VSCode,
Current Stage: When looking for a property value that's deep in a tree-like structure, one often has to check whether…
Here are the use cases.
a?.b // a == null ? undefined : a.b
a?.[x] // a == null ? undefined : a[x]
a?.b() // a == null ? undefined : a.b()
a?.() // a == null ? undefined : a()
You can stack the optional chaining operator. The initial examples in this article now become:
payload?.data?.items?. && ( /*.. whatever .. */ )
// if onClose is not a function, an error is thrown
The more code there is the more chances of human errors. Declarative style with functional programming patterns and constructs like ‘optional chaining’ help write code that is concise and less error prone.