Optional Chaining in React Native
In the June 2018 release of React Native (0.56.0) they had announced the enabling of optional chaining operator ?.
plugins. Previously we’ve to manually add babel-plugin for syntax-optional-chaining to use this operator. So, here comes the question; what is the purpose of this optional chaining operator thing?
Problems in Property Chaining
We normally encounter the state where an expected member of a property chain is undefined or null. Suppose we’re getting the data
from an API call; we expect user.profile.avatar
to exist but for some reason the profile
is missing from the user
object;
data = {
user: {
firstName: 'Uranium',
contactNo: '+88017261069XY'
}
};console.log(data.user.profile.avatar);>> Uncaught TypeError: Cannot read property 'avatar' of undefined
Let’s see some of the existing solutions that we can use to solve this issue -
Try-Catch
const avatar;try {
avatar = data.user.profile.avatar;
} catch (error) {
avatar = null;
}
Ternary Operator
const avatar = data.user === undefined
? undefined
: data.user.profile === undefined
? undefined
: data.user.profile.avatar;
Logic Expression
const avatar = data.user && data.user.profile && data.user.profile.avatar;
In my opinion, these procedures are a bit Ugly, Noisy, Burdensome, and Verbose. Here’s where optional chaining comes into action. We can have the fun of using it like this:
data = {
user: {
firstName: 'Uranium',
contactNo: '+88017261069XY'
}
};// doesn't throw error ✌️
console.log(data.user?.profile?.avatar);
That’s much easier, right? As we’ve seen the usefulness of this feature, we can go ahead and take a deep dive.
Array index Out of Bound is a common phenomenon in the programming world, optional chaining works for array property access too:
data = {
user: {
profile: {
friends: ['Goldie', 'Nowshad'],
}
}
};
function getFriends(data, index) {
return data.user?.profile?.friends?.[index];
}
We can also check the existence of a function:
data = {
user: {
profile: {
friends: ['Goldie', 'Nowshad'],
},
getFriends() {
return data.user.profile.friends
}
}
};data.user?.getFriends?.();
Expressions will not execute further if that chain is not complete. Under the hood, the expressions are practically transformed to this:
value === null ? value[expression] : undefined;
Basically in a short, we can sum up this like — nothing after the optional chain operator ?
will be executed if the value is undefined or null. So, as a whole optional chaining reduces the need for if
statements, imported libraries like lodash
, and the need for chaining with &&
logical operator.
Reference
Here’s one of the links to the proposal of adding optional chaining in Javascript, and this is the babel-plugin-proposal link. Finally the commit link of adding the optional-chaining plugin to RN 0.56