Safe navigation operator in Reactjs using JSX - javascript

I am using Reactjs via JSX. Is there any safe navigation operator to use in this method? I tried using question mark operator like "foo?.bar" but I got syntax error.

The safe navigation operator (aka. Elvis operator) is a proposal in draft status with TC39, so no. Not yet anyway (as of this writing).
But this ugly syntax will get you there without a library. Instead of ...
foo?.bar
... use this ...
(foo||{}).bar||{}
It's hard to read but it works and it isn't dependent on a library.
UPDATE: The proposal has reached stage 4, so it will be part of ES2020.

You can use from get method in lodash library, like this:
import { get } from 'lodash';
get(foo, 'bar1.bar2.bar3.bar4');

Now, there is a babel plugin called #babel/plugin-proposal-optional-chaining that solves this problem.

Related

How can I use the ?? operator in VueJs templates?

I am trying to build a component to handle the editing of a substructure of my data. This piece of data is an object but in the main object, it is optional. So when invoking component I am trying to use the ?? operator to pass in an empty object to avoid access of undef issue. I would also like to be able to use the ?. operator for the same reason. Like so.
<template>
<my-sub-component :value="value.scf_rule??{}" />
</template>
However, Vuejs doesn't really like the question marks in the HTML attributes on my template. I get the following error:
Syntax Error: SyntaxError: Unexpected token (1:93)
This should be a really simple lookup on the web but I have been looking for quite a while and it's not easy. It doesn't help that searching for question marks isn't really possible.
I've tried escaping it with a backslash, that doesn't seem to work. Anyone know how I can have an expression in my attribute that uses the question mark operator? I suppose I could define my own nvl utility function but that seems a tad silly.
If you remove any kind of build stack from the equation, you can use whatever your platform supports. Your browser then will run the code just as you author it.
Otherwise you are limited to what the acorn parser version used by your webpack/bundler supports (usually everything finalized in the spec and proposals that have reached stage 4). With Vue, you're probably using webpack.
If you are fine with your code being transpiled to older JS versions, use Babel along with the necessary plugins 1 2.

How can I make VSCode maintain proper syntax highlighting for .JS files after using Elvis (?) operator?

In my .js files, when I use an elvis operator const something = data?.info?.set , the entire file turns red after the line used.
How can I make VSCode recognize elvis operators and maintain syntax proper highlighting?
Note: I use metro-react-native-babel-preset and eslint, which by default allows for optionals in pure .js files (not typescript)
I have installed https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-typescript-next and also followed the instructions to enable it. However, my code is still pure red color starting the line after I use the ? operator.
VS Code 1.41 supports syntax highlighting and IntelliSense for optional chaining (?.) out of the box.
If you still see red highlighting with VS Code 1.41, either:
One of your installed extensions is causing this. ESlint for example
You are using an older typescript version in your workspace. Make sure to use TS 3.7+
My problem was solved by removing this plugin from VSCode :
EDIT: After OP's edit of the question, I tried to scour for some info. This is what I came up with:
Getting eslint right in React Native
VSCode Linter ES6 ES7 Babel linter
Optional chaining operator support in VSCode
I don't believe there's an Elvis operator in JS.
Instead, you can use the OR operator to return something specific without crashing it. So something like
const something = data.info.set || undefined;
Disable or remove this extension completely from your vs code
The Extension causing the syntax error, hopefully, it works for you as it did for me.

How to implement side effect on Observable retuned by HttpClient.get?

Does someone know how to use RxJS do operator on observer returned by angular's HttpClient.get method?
Versions:
angular: 5.2.1
rxjs: 5.5.6
With this version of angular I can't do this:
import { HttpClient } from '#angular/common/http';
...
constructor(
private http: HttpClient,
) { }
...
this.http.get<Item>(url)
.do(res => console.log(JSON.stringify(res)))
.share();
Instead I have to add new steps with pipes. I can do it with switchMap, map or share, but I can't figure out how to do it with do.
I found out that I can do import { _do } from 'rxjs/operator/do';, but when I'm trying to use it like this:
this.http.get<Item>(url)
.pipe(_do(res => console.log(JSON.stringify(res)))
or like this:
const observable = this.http.get<Item>(url);
observable.pipe(_do(observable, res => console.log(JSON.stringify(res)}));
I'm getting error:
[ts] The 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable<{}>'.
As pipeable operators documentation explains, pipeable do was renamed to tap, alongside with several others. This was done in order to avoid collisions with reserved JavaScript keywords.
Pipeable operators are supposed to be imported as
import { tap } from 'rxjs/operators/tap';
Notice that pipeable operators are located in rxjs/operators/..., while rxjs/operator/... imports are used to patch Observable.prototype.
There are no concerns that would prevent do operator from being used some Angular versions. Both import styles are supported and valid, as long as a developer understands that there are certain differences between patch operators and pipeable operators that make the latter preferable in some cases. They are explained on documentation page:
Any library that imports a patch operator will augment the Observable.prototype for all consumers of that library, creating blind
dependencies. If the library removes their usage, they unknowingly
break everyone else. With pipeables, you have to import the operators
you need into each file you use them in.
Operators patched directly onto the prototype are not "tree-shakeable" by tools like rollup or webpack. Pipeable operators
will be as they are just functions pulled in from modules directly.
Unused operators that are being imported in apps cannot be detected reliably by any sort of build tooling or lint rule. That
means that you might import scan, but stop using it, and it's still
being added to your output bundle. With pipeable operators, if you're
not using it, a lint rule can pick it up for you.
Functional composition is awesome. Building your own custom operators becomes much, much easier, and now they work and look just
like all other operators from rxjs. You don't need to extend
Observable or override lift anymore.
I fixed it with help of this answer.
Actually, I had wrong import. This code works:
import 'rxjs/add/operator/do';
...
this.http.get<Item>(url)
.do(res => console.log(JSON.stringify(res))

How to use "Object?.property" syntax in React

I can use this way to prevent undefined error when the object is undefined , but it not work in React. i want to know is this ES6’syntax or other syntax?
The safe navigation operator is a feature of Angular, and not part of the JavaScript langauge. As a result, it will not work in React applications.

Typescript Object destructuring results in "Property assignment expected."

I am transitioning a project from Babel to Typescript and receive the following compiler error:
error TS1136: Property assignment expected.
from code that looks like this:
var auth = {...this.props.auth};
This code previously worked fine under Babel, but causes the error above when attempting to compile via Typescript. Is object destructuring different in Typescript?
The feature you are looking for is Object spread/rest operators (proposed for ES7). It looks like it's planned but not yet implemented:
We want to wait for the proposal to reach Stage 3 before addressing this.
More info here.
Edit: The proposal is in stage-3. We'll likely see it drafted on ES2018 (ES9). Support has been added to TypeScript as well (starting from 2.1).

Categories

Resources