Content Source:
- blog.angular.io
Vue.nextTick allows you to do something after you have changed the data and VueJS has updated the DOM based on your data change, but before the browser has rendered those changed on the page.
// modify data vm.msg = 'Hello' // DOM not updated yet Vue.nextTick(function () { // DOM updated }
// usage as a promise (2.1.0+, see note below) Vue.nextTick() .then(function () { // DOM updated })
First GIF vs Second GIF
pic courtesy : medium.com
pic courtesy : medium.com
Can you see the difference?
The first gif uses $nextTick method
async handleFiles(fileList: FileList): Promise<void[]> { this.isFileUploaded = true; // does not work until all Promise are resolved await this.$nextTick(); // console.log(this.isFileUploaded) // true const directory = await carfsModule.setupSubDirectory(); ... }
isFileUploaded
is a state which triggers the UI change.isFileUploaded
state before Promise API call await carfsModule.setupSubDirectory()
will solve the issuethis.isFileUploaded = true; const directory = await carfsModule.setupSubDirectory(); /// ...
isFileUploaded
state is still updated AFTER / At the same time the Promise APIs are resolved [which is Second Gif ].isFileUploaded
state immediately (Before the Promise API) [which is First Gif ].this.isFileUploaded = true; // does not work until all Promise are resolved await this.$nextTick(); // console.log(this.isFileUploaded) // true const directory = await carfsModule.setupSubDirectory();
In node.js, nextTick helps its callback function to execute prior to other callback functions in Event loop.
setImmediate(() => { console.log('immediate'); }); process.nextTick(() => { console.log('nextTick'); }); setTimeout(() => { console.log('timeout'); }, 0); Promise.resolve().then(() => console.log('promise'));
has an output of :
nextTick promise timeout immediate
process.nextTick
executes prior to setImmediate
or setTimeout
.setImmediate
or setTimeout
.nextTick
has a priority over Promise.resolve
, setTimeout
, setImmediate
.
Let’s check this out example:
setTimeout(() => { console.log('timeout'); }, 0); Promise.resolve().then(() => console.log('promise')); console.log('helloworld3'); process.nextTick(() => { console.log('nextTick'); }); console.log('helloworld5');
has an output of:
helloworld3 helloworld5 nextTick promise timeout
In other words, isFileUploaded state will convert from false
to true
as a priority regardless of its place in the function.
async handleFiles(fileList: FileList): Promise<void[]> { // this.isFileUploaded = true; await this.$nextTick(); // this.isFileUploaded = true; const directory = await carfsModule.setupSubDirectory(); // this.isFileUploaded = true; }
process.nextTick
and Promise
are often called as microtask.pic courtesy : medium.com
For more Information and to build the website using Vue.js, Hire Vue.js Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop the custom website using Vue.js, please visit our technology page.
Content Source:
React 16.13.0 contains bugfixes and new deprecation warnings to help prepare for a future major release.
A React component should not cause side effects in other components during rendering.
It is supported to call setState
during render, but only for the same component. If you call setState
during a render on a different component, you will now see a warning:
Warning: Cannot update a component from inside the function body of a different component.
This warning will help you find application bugs caused by unintentional state changes.
In the rare case that you intentionally want to change the state of another component as a result of rendering, you can wrap the setState
call into useEffect
.
When dynamically applying a style
that contains longhand and shorthand versions of CSS properties, particular combinations of updates can cause inconsistent styling. For example:
<div style={toggle ? { background: 'blue', backgroundColor: 'red' } : { backgroundColor: 'red' } }> ... </div>
You might expect this <div>
to always have a red background, no matter the value of toggle
. However, on alternating the value of toggle
between true and false, the background color start as red
, then alternates between transparent
and blue
, as you can see in this demo.
React now detects conflicting style rules and logs a warning. To fix the issue, don’t mix shorthand and longhand versions of the same CSS property in the style
prop.
String Refs is an old legacy API which is discouraged and is going to be deprecated in the future
<Button ref="myRef" />
For example, it will fire if you use String Refs together with the Render Prop pattern:
class ClassWithRenderProp extends React.Component { componentDidMount() { doSomething(this.refs.myRef); } render() { return this.props.children(); } } class ClassParent extends React.Component { render() { return ( <ClassWithRenderProp> {() => <Button ref="myRef" />} </ClassWithRenderProp> ); } }
Code like this often indicates bugs. (You might expect the ref to be available on ClassParent
, but instead it gets placed on ClassWithRenderProp)
You most likely don’t have code like this. If you do and it is intentional, convert it to React.createRef()
instead:
class ClassWithRenderProp extends React.Component { myRef = React.createRef(); componentDidMount() { doSomething(this.myRef.current); } render() { return this.props.children(this.myRef); } } class ClassParent extends React.Component { render() { return ( <ClassWithRenderProp> {myRef => <Button ref={myRef} />} </ClassWithRenderProp> ); } }
React.createFactory
is a legacy helper for creating React elements. This release adds a deprecation warning to the method. It will be removed in a future major version.
Replace usages of React.createFactory
with regular JSX. Alternately, you can copy and paste this one-line helper or publish it as a library:
let createFactory = type => React.createElement.bind(null, type);
When React 16 was released, createPortal
became an officially supported API.
However, we kept unstable_createPortal
as a supported alias to keep the few libraries that adopted it working. We are now deprecating the unstable alias. Use createPortal
directly instead of unstable_createPortal
. It has exactly the same signature.
React adds component stacks to its development warnings, enabling developers to isolate bugs and debug their programs. This release adds component stacks to a number of development warnings that didn’t previously have them. As an example, consider this hydration warning from the previous versions:
pic courtesy: reactjs.org
While it’s pointing out an error with the code, it’s not clear where the error exists, and what to do next. This release adds a component stack to this warning, which makes it look like this:
pic courtesy: reactjs.org
This makes it clear where the problem is, and lets you locate and fix the bug faster.
This release contains a few other notable improvements:
shouldComponentUpdate
. This shouldn’t affect most code, unless you have side effects in shouldComponentUpdate
. To fix this, move the code with side effects into componentDidUpdate
.onMouseEnter
now doesn’t trigger on disabled <button>
elements.version
export since we published v16. This release adds it back. We don’t recommend using it in your application logic, but it’s useful when debugging issues with mismatching / multiple versions of ReactDOM on the same page.React v16.13.0 is available on the npm registry.
To install React 16 with Yarn, run:
yarn add react@^16.13.0 react-dom@^16.13.0
To install React 16 with npm, run:
npm install --save react@^16.13.0 react-dom@^16.13.0
We also provide UMD builds of React via a CDN:
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script> <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
For more Information and to build a website using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“. To develop your custom website using React JS, please visit our technology page.
Content Source:
The 9.0.0 release of Angular is here! This is a major release that spans the entire platform, including the framework, Angular Material, and the CLI.
Version 9 moves all applications to use the Ivy compiler and runtime by default. In addition to hundreds of bug fixes, the Ivy compiler and runtime offers numerous advantages:
Here’s a breakdown of some of the more notable improvements.
The Ivy compiler has been designed to remove parts of Angular that aren’t being used via tree-shaking and to generate less code for each Angular component.
With these improvements, small apps and large apps can see the most dramatic size savings.
Small apps could see around a 30% decrease in bundle size, large apps will see a 25–40% decrease, and medium apps decrease minimally. – pic courtesy: blog.angular.io
We have also revamped the implementation of TestBed in Ivy to make it more efficient.
Previously, TestBed would recompile all components between the running of each test, regardless of whether there were any changes made to components (for example, through overrides).
In Ivy, TestBed doesn’t recompile components between tests unless a component has been manually overridden, which allows it to avoid recompilation between the grand majority of tests.
With this change, the framework’s core acceptance tests are about 40% faster. We would expect users to see their own application test speeds to be around 40–50% faster.
Ivy provides you with more tools to debug your applications. When running an application in Dev Mode with the Ivy runtime, we now offer the new ng object for debugging.
pic courtesy: blog.angular.io
Ivy also improves the stack trace for debugging issues such as the ExpressionChangedAfterItHasBeenCheckedError. Previously the stack trace could be unhelpful:
pic courtesy: blog.angular.io
With Ivy, you see a more useful stack trace that allows you to jump directly to the template instruction with the expression that has changed.
pic courtesy: blog.angular.io
For example, if you click on AppComponent_Template in the stack trace above, you can see the specific line in the generated code where the error is being thrown:
If you’re so inclined, you can also step into any of these framework instructions to walk through how the framework creates or updates your components.
The Ivy compiler and runtime provides improvements for handling styles. Previously, if an application contained competing definitions for a style, those styles would destructively replace each other. With Ivy, the styles are merged in a predictable way.
Consider the following template and component snippets:
<my-component style="color:red;" [style.color]="myColor" [style]="{color: myOtherColor}" myDirective></div>
@Component({ host: { style: "color:blue" },... }) ... @Directive({ host: { style: "color:black", "[style.color]": "property" },... }) ...
Previously, whichever binding was evaluated last would win, and this could depend on the timing of changes to these expressions. If myColor and myOtherColor both were undefined, the static ‘red’ style would be ignored.
With version 9, you can manage your styles through a clear, consistent order of precedence that isn’t dependent on timing. The most specific styles always have the highest precedence. For example, a binding to [style.color] overrides a conflicting binding to [style].
However, for backwards compatibility reasons, we have left [ngStyle] and [ngClass] bindings behavior the same as before. When their binding values are updated, the new values will override any competing bindings.
You can read more about styling precedence rules in the Template Syntax guide in the documentation.
As a side effect of the styling refactoring, you can now also bind to CSS custom properties (also known as CSS variables).
<div [style.--main-border-color]=" '#CCC' "> <p style="border: 1px solid var(--main-border-color)">hi</p> </div>
Thanks to Ivy’s new architecture, we’ve made significant improvements to the compiler’s performance.
We measure our compiler’s performance in terms of the overhead on top of a plain TypeScript compilation of an application. For our documentation app (angular.io), this overhead decreased from 0.8x to 0.5x with Ivy, an improvement of nearly 40%.
These improvements mean that AOT builds can be noticeably faster. Thanks to this speedup, for the first time ever we’re using AOT even for dev-mode builds. This means that `ng serve` now benefits from the same compile-time checking as production builds, significantly improving the developer experience for Angular.
Thanks to the changes in the compiler and runtime, we also no longer require entryComponents. These components will be discovered and compiled automatically by their usage.
For more information and to develop your web apps using Angular, Hire Angular Developer from us as we provide you high-quality solution by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop the custom web app using Angular, please visit our technology page.
Content Source:
When you write a class in JavaScript, you might have had to add more features to the methods in a class. But sometimes they look quite nasty and messy.
How can you make the process more elegant? In this post, we will talk about a promising feature, a decorator.
This feature isn’t included in the newest ECMA-262, JavaScript in other words. You should always use Babel to use this in your project.
The examples I’ve attached to this post were written in JSFiddle, with the Babel + JSX configuration. If you want to use this feature in your project, you ought to set up Babel on your own.
class Medium { constructor(writer) { this.writer = writer; } getWriter() { return this.writer; } }
There’s a class, Medium
, that takes the name of the writer in its constructor. And there’s a function that returns the writer’s name.
Let’s create a property that is of Medium
type.
const medium = new Medium('Jane'); const fakeMedium = { writer: 'Fake Jane', getWriter: medium.getWriter, };
medium
is created using Medium
‘s constructor function, unlike fakeMedium
which is an object literal. But it has the same properties as medium
.
Now, let’s compare the result of getWriter
from each.
medium.getWriter(); // Jane fakeMedium.getWriter(); // Fake Jane
Why are the values different?
It’s because JavaScript’s normal function this
is bound to the object that actually invokes the function.
medium.getWriter()
is called by the medium
object, however, fakeMedium.getWriter()
is called by fakeMedium. So, the this
inside the function, getWriter, looks up the value from fakeMedium
.
This article outlines the difference between normal functions and arrow functions.
To get the same result as when medium.getWriter
is called, let’s use Object.defineProperty
. What Object.defineProperty
does is define new properties on the object or modify the existing properties on the object and then it returns the object.
const fakeMedium = { ... }; let isDefining; let fn = fakeMedium.getWriter; Object.defineProperty(fakeMedium, 'getWriter', { get() { console.log('Access to getWriter'); if (isDefining) { return fn; } isDefining = true; const boundFn = this.getWriter.bind(medium); isDefining = false; return boundFn; } });
Whenever fakeMedium.getWriter
is called, Access to getWriter
will be printed twice. But why twice?
fakeMedium.getWriter()
, its getter-mode is detected and runs the customized get
method.get
method, the getWriter
is newly bound by medium
– this.getWriter.bind(medium)
. Here, this
refers to fakeMedium
itself. So it’s the same as fakeMedium.getWriter.bind(medium)
. That’s why its get
is called once again.isDefining
is set to true, so the codes under the if-condition won’t be executed until isDefining
is set back to false again.But this way is really a pain in the neck. Because every time you make a new instance of Medium
, you should do this again.
Can’t we do this in a more elegant way?
Any function can be a decorator. Basically, you can use a decorator for either a class or a method in a class. It takes three arguments – target, value, and descriptor.
function decorator(target, value, descriptor) {}
target
refers to either the class or a prototype of the class.value
is undefined
for a class and is the name of the method for a method.descriptor
is an object that contains definable properties on an object – such as configurable, writable, enumerable, and value. It’s undefined
for a class.function autobind(target, value, descriptor) {} class Medium { ... @autobind getWriter() { return this.writer; } }
A decorator is used with an at sign (@
), with the name of the function that you’ll use as a decorator — and it takes three arguments as we just explained.
function autobind(target, value, descriptor) { const fn = descriptor.value; return { configurable: true, get() { return fn.bind(this); } } }
descriptor.value
is the name of the function on which you put the decorator function – in this case, it’s getWriter
itself.
Note that the return value of autobind
is a new object, then getWriter
adopts the return value to its environment.
What’s good about using decorators is that they are reusable. All you need to do after defining the decorator function is merely to write @autobind
on functions.
Here’s another example of making class member properties read-only, which is even easier.
function readonly(target, value, descriptor) { descriptor.writable = false; return descriptor; } class Medium { @readonly signUpDate = '2019-04-23'; } const medium = new Medium(); medium.signUpDate; // 2019-04-23 medium.signUpDate = '1999-11-11'; medium.signUpDate; // 2019-04-23 ^ The value isn't changed!
This time, the descriptor of the property has been changed by setting the writable
property as false
and that is all. Dead simple. Right?
Here’s the comparison of the full code.
class Medium { constructor(writer) { this.writer = writer; } getWriter() { console.log(this.writer); } } const medium = new Medium('Jane'); const fakeMedium = { writer: 'Fake Jane', getWriter: medium.getWriter, }; medium.getWriter(); // Jane fakeMedium.getWriter(); // Fake Jane /* Do auto-binding job for the same values */ let isDefining; let fn = fakeMedium.getWriter; Object.defineProperty(fakeMedium, 'getWriter', { get() { if (isDefining) { return fn; } isDefining = true; const boundFn = this.getWriter.bind(medium); isDefining = false; return boundFn; } }); medium.getWriter(); // Jane fakeMedium.getWriter(); // Jane
function autobind(target, value, descriptor) { const fn = descriptor.value; return { configurable: true, get() { return fn.bind(this); } } } class Medium { constructor(writer) { this.writer = writer; } @autobind getWriter() { console.log(this.writer); } } const medium = new Medium('Jane'); const fakeMedium = { writer: 'Fake Jane', getWriter: medium.getWriter, }; medium.getWriter(); // Jane fakeMedium.getWriter(); // Jane
Try it out by yourself!
A decorator is very useful, powerful, amazing, and remarkable. Honestly, we don’t see any reason to say no to use this awesome feature.
But, remember that it’s still at stage 2 and the way we used this in this post is more like Babel’s style, not the currently proposed one at stage 2. So, things might be different, like how to use it or what you can actually do with it.
So, we absolutely recommend you use this feature with the appropriate Babel configurations for your project but we also want to mention to keep an eye on this feature in TC39.
For more information and to develop your web app using front-end technology, Hire Front-End Developer from us as we give you a high-quality solution by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“. To develop your custom website using JS, please visit our technology page.
Content Source:
ECMAScript has grown to be one of the world’s most widely used general-purpose programming languages. ECMAScript is based on several originating technologies, the most well-known being JavaScript (Netscape) and JScript (Microsoft). Here are the new features of ES2020.
Now, you can import a file dynamically.
import { max } from '../math.js'; const nums = [1, 2, 3]; max(...nums); // 3
This has been the way we could import a file. And the JavaScript engine reads the modules in the file and bring them into the file where those modules are called. But now, you can do this as follows.
const numbs = [1, 2, 3]; if (numbs.length) { const math = '../math'; import(math) .then(module => { module.max(...numbs); }) }
A dynamic import returns a promise. Which means you can write it this way as well.
const math = '../math.js'; const module = await import(math); module.max(...numbs);
Why this feature is good is that you can use a dynamic import in a regular JavaScript code like the example above.
Here’s the browser support for Dynamic Import.
When you had to add two numbers that are too big enough to cause an overflow, weren’t you suffered?
Number.MAX_VALUE * 2 // Infinity
BigInt is a savior in this case.
You can make a BigInt by calling BigInt()
with parenthesis or 2n
with ‘n’ at the end of a number.
const num = 2; const bigNum = BigInt(num); bigNum; // 2n bigNum === 2n; // true
You can also add, subtract, multiply and divide it.
const bigN = BigInt(10); bigN + bigN; // 20n bigN * 3n; // 30n bigN - BigInt('55'); // 45n bigN / 3n; // 3n
Note that bigN / 3n
returns 3n
, not 3.33333n
. Because as you also can assume from its name, it only handles the integers. So bigN / 3n
is similar to Math.floor(10 / 3)
.
However, unfortunately, you can’t make a BigInt with a float number. And also, you can’t use a BigInt and a Number together, either.
BigInt(3.3); // Uncaught RangeError BigInt('3.3'); // Uncaught SyntaxError BigInt(1) + 1; // Uncaught TypeError // Cannot mix BigInt and other types
Instead, the only allowed case to mix the operations is when you compare the size of the operations.
BigInt(1) < 2 // true
And a BigInt can be evaluated like a Number if it’s in if condition.
function print(n) { if (BigInt(n)) { console.log('hi'); } else { console.log('bye'); } } print(1); // hi print(0); // bye
Here’s the browser support for BigInt
This is quite similar to Promise.all , but there’s a significant difference between them. Promise.all waits for all the promises being fulfilled or an any promise being rejected. On the other hand, Promise.allSettled doesn’t care about that. What it cares is to know if all the promises are done, whichever their status is. So every input promise could be fulfilled or rejected, but it doesn’t matter to Promise.allSettled . Just all of them have to be done.
const promises = [ Promise.resolve(1), Promise.reject(2), Promise.resolve(3) ]; const onResolve = (data, prefix) => { console.log(prefix, 'Resolved with', data); }; const onReject = (err, prefix) => { console.log(prefix, 'Rejected with', err); }; Promise.all(promises) .then(onResolve.bind(null, 'all')) .catch(onReject.bind(null, 'all')); // Result: // all Rejected with 2 Promise.allSettled(promises) .then(onResolve.bind(null, 'allSettled')) .catch(onReject.bind(null, 'allSettled')); // Result: // allSettled Resolved with // [ // { // "status": "fulfilled", // "value": 1 // }, // { // "status": "rejected", // "reason": 2 // }, // { // "status": "fulfilled", // "value": 3 // } // ]
This might be quite useful when you want to do some works before some action, for example, getting all of the required data before the user sees the list page. But the user could see the empty items because the fetch might be failed.
Here’s the browser support for Promise.allSettled
.
This is lit. It’s dead simple and easy to use.
globalThis
refers to the global this
context on which your running context is. If you’re on Browsers, globalThis
will be this , if you’re on Node, globalThis
will be global
. Hence no need to think about the different environmental issues anymore.
// worker.js globalThis === self // node.js globalThis === global // browser.js globalThis === window
And this is how it works under the hood, but don’t use it in your code!
var getGlobal = function () { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } throw new Error('unable to locate global object'); };
Here’s the environmental support for gloablThis
.
For more information and to design a website using front-end technology, Hire Front-End Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“. To develop your custom website using JS, please visit our technology page.
Content Source:
JavaScript is the standard technology for implementing a seamless interaction between a user and the web page. Almost all modern browsers support it. It is the main technology behind driving the modern UX and/or server-side frameworks such as Angular, Node.JS and ReactJS. Here are top 5 best practices to write more robust JavaScript.
If you don’t know what a factory function is, it’s simply a function (that isn’t a class or constructor) that returns an object. This simple concept allows us to take advantage of JavaScript and its features to create powerful robust applications.
It’s important to know that they’re no longer factory functions when they’re called with the new
keyword.
Factory functions can be used to easily produce instances of objects without having anything to do with classes or the new
keyword.
What it essentially means is that they ultimately become treated as just functions, which means they can be used to compose objects, functions, and even promises. This means you can mix and match factory functions together to create an enhanced factory function, then continue composing with other functions or objects to create even further enhanced ones. The possibilities are endless.
When we take that into consideration and combine it with good code practices, it really begins to shine.
Here is a simple example of a factory function:
function createFrog(name) { const children = [] return { addChild(frog) { children.push(frog) }, } } const mikeTheFrog = createFrog('mike')
When you’ve used factory functions enough, you begin to realize that compared to its class constructor counterpart, it promotes stronger reusability. This results in less code, an easier time refactoring since factory functions ultimately return arbitrary objects, and an easier time managing one code to another.
If you’re new to JavaScript, this section might be a little new to you as it was for me for the first two years of my experience with JavaScript.
(Keep in mind that this does not apply to classes because classes already attach methods onto their prototypes.)
Here’s an example of a constructor:
function Frog(name, gender) { this.name = name this.gender = gender } Frog.prototype.leap = function(feet) { console.log(`Leaping ${feet}ft into the air`) }
Why do this instead of directly attaching the leap method, like in the example below?
function Frog(name, gender) { this.name = name this.gender = gender this.leap = function(feet) { console.log(`Leaping ${feet}ft into the air`) } }
When we attach methods directly on the prototype, they get shared among all instances created by the constructor.
In other words, using the last example, if we created three separate Frogs (from this.leap = function() {…}), then we end up creating three separate copies. This is a problem because the leap method will always stay the same and doesn’t need to have its own copy to its instance.
Ultimately, this results in lower performance, when it could have been avoided. The this.name and this.gender properties need to be defined on the instance because in real life, frogs probably have their own names and gender so it makes sense to have them created on the instance level.
Here’s an example on GitHub of this approach used by the popular request package.
This practice works so well that it’s in extensive use today. If you’re a React developer, you’ve probably already been seeing this every day, especially when you’ve been working with Redux.
Using similar approaches also makes it extremely easy for you in your development flow since it even documents itself extremely well:
function createSpecies(type, name, gender) { if (type === 'frog') { return createFrog(name, gender) } else if (type === 'human') { return createHuman(name, gender) } else if (type == undefined) { throw new Error('Cannot create a species with an unknown type') } } const myNewFrog = createSpecies('frog', 'sally', 'female')
TypeScript has become widely adopted in the JavaScript community due to its ability to provide a strong defense for type safety as well as its ability to help us catch bugs before they even occur.
Using TypeScript will enable your compiler to detect and show warnings about any potential errors in code before the code even runs.
But that’s not even close to a complete list of reasons why adopting TypeScript is good for any situation. One of the best things about TypeScript is that it allows you to use new features in JavaScript before they’re supported by major browsers since they get compiled down to earlier versions of JavaScript, ultimately being able to run in old browsers.
try/catch
when using JSON.parse
or JSON.stringify
In JavaScript, when we pass JSON as input to the JSON.parse
method, it expects a properly formatted JSON as the first argument. If it’s formatted incorrectly, it will throw a JSON parse error.
The danger coming from JSON parse errors is that receiving invalid JSON crashes your app. We’ve recently been in a situation at work where one of our web projects was failing because another internal package did not wrap a JSON.parse
in a try/catch
. This ended up making a web page fail, and there was no way to get past this error unless the internal package fixed it. This happened because the JavaScript runtime was broken.
SyntaxError: Unexpected token } in JSON at position 107
You shouldn’t always expect valid JSON input as it can receive weird characters like the >character, which is not uncommon today.
For more information and to design a website using front-end technology, Hire Front-End Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“. To develop your custom website using JS, please visit our technology page.
Content Source:
In our previous blog post, we learned about “Object Destructuring”. Next, in this post let’s take a tour of “Array Destructuring”.
Array destructuring works the same as object destructuring but instead of using name to identify the property as in object destructuring, we identify it by position in array starting with position zero.
const months = ["January", "February"]; console.log(months[0]); // January console.log(months[1]); // February
const months = ["January", "February"]; const [firstMonth, secondMonth] = months; console.log(firstMonth); // January console.log(secondMonth); // February
As you can see, the value from the array months with index 0 get assigned to firstMonth variable and index 1 value will be assigned to secondMonth variable.
If we want only the first value we can also do that as
const months = ["January", "February"]; const [firstMonth] = months; console.log(firstMonth); // January
But what if we want only second month and don’t want to create variable firstMonth if we are not using it. we can skip it as shown below.
const months = ["January", "February"]; const [,secondMonth] = months; console.log(secondMonth); // February
Note, there is comma before the secondMonth variable which will allows us to skip the creation of variable. So if we want to get the 3rd element of the array we can add one more extra comma.
const months = ["January", "February", "March"]; const [,,thirdMonth] = months; console.log(thirdMonth); // March
We can also assign the default value if the value does not exists.
const months = []; const [ firstMonth = "January" ] = months; console.log(firstMonth); // January
Suppose you want to swap 2 numbers.
let x = 10, y = 20; let temp; // Swap the x and y temp = x; x = y; y = temp; console.log(x, y); // 20 10
const [y, x] = [10, 20]; console.log(x, y); // 20 10
We can also use the rest operator which is three dots combined with array destructuring.
const months = ["January", "February", "March"]; const [firstMonth, ...restMonths] = months; console.log(firstMonth); // January console.log(restMonths); // ["February", "March"]
We can extend this further also.
const months = ["January", "February", "March", "April"]; const [firstMonth, secondMonth, ...restMonths] = months; console.log(firstMonth); // January console.log(secondMonth); // February console.log(restMonths); // ["March", "April"]
Now we will look into some complex examples of destructuring.
Example 1:
const users = [ { name: 'David', age: 20 }, { name: 'Billy', age: 40 }, ];
Now, suppose we want to get the first user object.
const [firstUser] = users; console.log(firstUser); // {name: "David", age: 20}
What if we want to get the name from the first user object?
const [{ name }] = users; console.log(name); // David
First to get the 1st object of the array, we used the following.
const [firstUser] = users;
Now from that object we want name property, so we use object destructuring syntax where the variable name has to match the property name of the object so we destructured it as
const [{ name }] = users;
Example 2:
Now consider we have visitedCountries object.
const visitedCountries = { countries: ["USA", "JAPAN"] };
How can we get the first country from the list of countries?
const { countries: [ firstCountry ] } = visitedCountries; console.log(firstCountry); // USA
and how to get the second country?
const { countries: [ , secondCountry ] } = visitedCountries; console.log(secondCountry); // JAPAN
Example 3:
Consider, we have a user’s array. Each array represents the name, country, age.
const users = [ ["David", "USA", 30], ["Billy", "Japan", 35], ["Mike", "Singapore", 50] ];
How can we convert it to an array of objects as shown below?
const convertedUsers = [ { "name": "David", "country": "USA", "age": 30 }, { "name": "Billy", "country": "Japan", "age": 35 }, { "name": "Mike", "country": "Singapore", "age": 50 } ]
We can use the map method and array destructuring here.
const convertedUsers = users.map(function([name, country, age]) { return { name: name, country: country, age: age }; }); console.log(convertedUsers); /* output [ { "name": "David", "country": "USA", "age": 30 }, { "name": "Billy", "country": "Japan", "age": 35 }, { "name": "Mike", "country": "Singapore", "age": 50 } ] */
As you can see from the above code.
return { name: name, country: country, age: age };
the key and value are same, so we can further simply it using ES6 Object Shorthand syntax as
const convertedUsers = users.map(function([name, country, age]) { return { name, country, age }; });
This is still taking three lines of code so we can further simplify it using arrow function as
users.map(([name, country, age]) => ({ name, country, age }));
Here we are implicitly returning the object { name, country, age } by adding it inside the round brackets ().
The output is same as above but its easy to understand and will save from typing some extra characters.
For more Information and to build a website using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“. To develop your custom website using React JS, please visit our technology page.
Content Source:
In this blog, we will see a very popular concept in ES6 known as destructuring. It’s one of the most widely used feature in ES6. In this article, we will see how we can apply it in our code and take advantage of this new syntax to write code that is easy to understand and to make the code shorter.
So Let’s get started.
Consider, we have following object.
const post = { image: 'http://unknown-site.com/image.jpg', likes: 200, comments: 400, date: '2019–12–20' };
If we want to get all the values from the object, Using ES5 Code we can write it as
const image = post.image; const likes = post.likes; const comments = post.comments; const date = post.date;
This is too much code and there is the repetition of each property in each line.
So we can write the same code using ES6 Object destructuring in a single line.
const { image, likes, comments, date } = post;
The code above creates local variables with the same name as the properties of the post object.
So it means, For ex. creating a local variable with the name image and take the value from post.image.
One thing to note is that the name used inside curly brackets has to match with the property name
So we cannot do something like this
const { new_image } = post;
This will result in an error because there is no new_image property to destructure in the post object.
It’s not necessary, to destructure all the properties from post object. We can only take the properties which we need
const { image } = post; // The above line is same as const image = post.image
We can also assign default values to the destructured properties.
Suppose, if we don’t have an image for the post as
const post = { likes: 200, comments: 400, date: '2019–12–20' };
We can use default parameter syntax to set default image using assignment operator as
const post = { likes: 200, comments: 400, date: '2019–12–20' }; const { image = 'http://unknown-site.com/defaultimage.jpg', likes, comments, date } = post; console.log(image); // http://unknown-site.com/defaultimage.jpg console.log(likes); // 200 console.log(comments); // 400 console.log(date); // 2019–12–20
Obviously, if we have the image property in the post object, that will be used instead of the default value like
const post = { image: 'http://unknown-site.com/image.jpg', likes: 200, comments: 400, date: '2019–12–20' }; const { image = ‘http://unknown-site.com/defaultimage.jpg', likes, comments, date } = post; console.log(image); // http://unknown-site.com/image.jpg console.log(likes); // 200 console.log(comments); // 400 console.log(date); // 2019–12–20
There are situations when we already have another variable with the same name in the current scope as the destructured property so it will create conflict and will result in an error. To fix this, we can use the renaming syntax of object destructuring as below
const { date: post_date } = post; console.log(post_date); // 2019–12–20
Here we are taking the date property and instead of creating local date variable we are renaming it to post_date so if you try to print the date variable value, you will get an error because it does not exist as we have renamed it to post_date now.
const { date: post_date } = post; console.log(post_date); // 2019-12-20 console.log(date); // error: date is not defined
We can also combine the default value and renaming syntax together like
const post = { likes: 200, comments: 400 }; const { date: post_date = '2019-12-10'} = post; console.log(post_date); // 2019-12-10
In the above code, in the highlighted code we are saying, take the date property from post object and rename it to post_date. If the date property does not exist then assign a default value of 2019–12–10 to post_date variable.
Suppose, we have a registerUser function which accepts a user object as a parameter.
function registerUser(user) { // David 20 New York david@11gmail.com console.log(user.name, user.age, user.location, user.email); } const user = { age: 20, name: 'David', location: 'New York', email: 'david@11gmail.com' }; registerUser(user);
We can use destructuring syntax here to simplify the code.
function registerUser({ name, age, location, email}) { // David 20 New York david@11gmail.com console.log(name, age, location, email); } const user = { age: 20, name: 'David', location: 'New York', email: 'david@11gmail.com' }; registerUser(user);
As you can see the function is simplified a lot. We no longer need to refer to the user object every time to get the value again in the function. Also the order in which its destructured does not matter and so is the case with which property to destructure.
function registerUser({ location, age }) { console.log(location, age); // New York 20 } const user = { age: 20, name: 'David', location: 'New York', email: 'david@11gmail.com' }; registerUser(user);
In the above code, we are accessing location before age in the function declaration which is fine because while destructuring the property name is used to destructure and not the position of the property.
Now consider, while registering, the name is optional field so we can set it to default value.
function registerUser({ name = 'Unknown', age, location }) { console.log(name, age, location); // Unknown 20 New York } const user = { age: 20, location: 'New York', email: 'david@11gmail.com' }; registerUser(user);
Now consider, user has already registered with email and we are updating his profile so everything is optional now so we can simplify it as
function updateUser({ name = 'Unknown', age = 0, location = 'Unknown' }) { console.log(name, age, location); // Unknown 0 Unknown } updateUser({});
For better readability, we have added each object property on separate line which is a valid syntax and you can also do it, if there are multiple properties on single line just for readability purpose.
But this does not look good, because we need to pass empty object to the updateUser function every time.
We can fix this by setting the default object if we don’t pass it.
function updateUser({ name = 'Unknown', age = 0, location = 'Unknown' } = {} ) { console.log(name, age, location); // Unknown 0 Unknown } updateUser();
Wow, that’s so cool. Now we can pass only values which are provided by user and others will be set to default values as shown below
function updateUser({ name = 'Unknown', age = 0, location = 'Unknown' } = {} ) { console.log(name, age, location); } updateUser({ name: 'David' }); // David 0 Unknown updateUser({ age: 20 }); // Unknown 20 Unknown updateUser(); // Unknown 0 Unknown
Now, you can understand the power of destructuring.
In our next blog, we will cover another ES6 destructuring feature called “Array Destructuring”.
For more Information and to build a website using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“. To develop your custom website using React JS, please visit our technology page.
Content Source:
Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and returns HTML via a render function. In this article, we will be looking at five React components that are useful in upcoming year as listed below.
Grommet is component library intended to help you in the task of creating your own websites simply by mixing and matching parts. That being said, this one has a strong focus on accessibility (by providing features such as keyword navigation, screen reader tags and so on), responsiveness and theming.
pic courtesy: blog.bitsrc.io
And if you’re not designed-inclined, which some developers aren’t they even provide you with a design kit and a complete icon set.
The design kit comes in different flavors such as Sketch for MacOS (seen in the screenshot below), Adobe XD and more.
pic courtesy: blog.bitsrc.io
Finally, the icon set can be seen in full on their site, but the image below shows how easy it is to install them into your project and add them to your code.
pic courtesy: blog.bitsrc.io
Much like the React Spinner, React Virtualized is meant to solve a single problem: efficiently rendering lists and tabular data in your pages.
Those edge cases and others are the ones this particular project is attempting to tackle.
pic courtesy: blog.bitsrc.io
Their website has a very simple, yet powerful demo you can play around with and understand the power this library brings to the mix. Change the numbers around and add copious amount of elements to your lists and see how easy it can adapt. Then think about how much code you’d have to write to make your own lists as flexible and then download React Virtualized.
react-desktop is a JavaScript library built on top of Facebook’s React library, which aims to bring a native desktop experience to the web, featuring many macOS Sierra and Windows 10 components. react-desktop works perfectly with NW.js and Electron.js, but can be used in any JavaScript powered project!
Take a look at the following screenshots to understand what we mean by that.
pic courtesy: blog.bitsrc.io
pic courtesy: blog.bitsrc.io
As you can see, with this library you can perfectly reproduce the desktop experience using JavaScript, which means you can create actual desktop applications using Electron.js or just add a very interesting look&feel to your web apps.
If you’re looking for an easy way to develop desktop applications using web technologies, we highly recommend doing so with React Desktop and Electron.js.
To build your own team’s library, without tons of overhead, try using Bit.dev. If a component library is like a music CD-Album, then bit.dev is like iTunes or Spotify for UI components. It kills 90% of the overhead, it’s scalable and it provides many enhanced features for shared components:
pic courtesy: blog.bitsrc.io
Here’s a short example, using a simple to-do app:
git clone https://github.com/giteden/basic-todo-app.git
Let’s say we want to export our app’s components to a shared collection (library)
Initialize a workspace and log in:
$ cd basic-todo-app
$ bit init
$ bit login
Add (all) components:
$ bit add src/components/*
Configure a React compiler (components are built independent of your project’s build configurations) :
$ bit import bit.envs/compilers/react --compiler
Tag and export to a shared collection (create your own collection in bit.dev):
$ bit tag --all 1.0.0
$ bit export username.collection
Rebass is a tiny UI components library capable of creating a very powerful set of themeable UI elements based on the Styled System library.
pic courtesy: blog.bitsrc.io
Some of the key features of this library are:
For more Information and to build a website using React JS, Hire React Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.To develop your custom website using React JS, please visit our technology page.
Content Source:
Before we get started, let’s first understand what we are building. The goal is to create a Vue.js component to display an image, but it should only download that image when it is in the viewport. In other words, if we have a large list of images, only the ones the user actually needs to see will be downloaded. This will speed up our apps.
Here’s the goals:
<img>
tagsWe know we will need an <img>
tag, so let’s start there. For accessibility purposes, images should always have an alt attribute, even if it’s empty. We can easily pull the alt attribute from the $attrs
or fall back to an empty string.
<template> <img :alt="$attrs.alt || ''" /> </template>
Now, something we need to fix is that we don’t actually want to set the image src attribute right away because that would cause it to download immediately.
Instead, what we want is a tiny transparent PNG that we can use as a placeholder for the image src
. Using a placeholder instead of an empty value will cause the image to take up space on the page while it waits to download the real image.
For this to work properly, we need to hijack the src attribute by expecting it as a prop
. We also need to tap into the <img>
width and height attributes to create a tiny transparent PNG with an HTML canvas, and export it as a computed property called dataUrl
.
<template> <img :src="dataUrl" :alt="$attrs.alt || ''" /> </template> <script> export default { props: { src: { type: String, required: true, }, }, computed: { dataUrl() { const { width, height } = this.$attrs if (!width || !height) return "" // create a tiny png with matching aspect ratio as img const w = 100 const canvas = document.createElement("canvas") canvas.width = w canvas.height = (height / width) * w return canvas.toDataURL() }, }, } </script>
Alright, so we’ve got a transparent image when the component lands on the page. Now we need to figure out how to set our src attribute to the real image when the component is in view.
For that, we will hook into the mounted lifecyle event and use Intersection Observer. Before we get to that, however, we need to do a little refactor.
We need a <div>
to wrap our <img>
(This will make more sense later). Divs and images behave slightly different, so we also nee a little bit of style to make sure it still behaves like a native <img>
.
<template> <div class=" app-img "> <img :src="dataUrl" :alt="$attrs.alt || ''" v-bind="$attrs" /> </div> </template> <script> export default { inheritAttrs: false, props: { src: { type: String, required: true, }, }, computed: { dataUrl() { const { width, height } = this.$attrs if (!width || !height) return "" // create a tiny png with matching aspect ratio as img const w = 100 const canvas = document.createElement("canvas") canvas.width = w canvas.height = (height / width) * w return canvas.toDataURL() }, }, } </script> <style> .app-img { display: inline-block; } </style>
Any attributes it receives should be bound to our tag and not the
<div>
. We’ll use v-bind
and $attrs
for the image, and tell the component not to add the default attributes to the root <div>
by setting inheritAttrs
to false.
we’re ready to implement the Intersection Observer for lazy-loading. we won’t go into too much detail on how Intersection Observer works, but in the mounted hook, we create an IntersectionObserver
that watches for the component (via $el
) to enter the viewport. When it does, we add an event handler to the image’s ‘load’ event, and assigns the image’s src attribute (which begins loading it). We also do a bit of cleanup work to the beforeDestroy
hook just in case.
<template> <div class=" app-img "> <img :src="dataUrl" :alt="$attrs.alt || ''" v-bind="$attrs" /> </div> </template> <script> export default { inheritAttrs: false, props: { src: { type: String, required: true, }, }, computed: { dataUrl() { const { width, height } = this.$attrs if (!width || !height) return "" // create a tiny png with matching aspect ratio as img const w = 100 const canvas = document.createElement("canvas") canvas.width = w canvas.height = (height / width) * w return canvas.toDataURL() }, }, mounted() { const { src, $el } = this const observer = new IntersectionObserver(([entry]) => { const img = $el.querySelector("img") if (entry.isIntersecting) { // Element is in viewport img.src = src observer.disconnect() } }) observer.observe($el) this.$once("hook:beforeDestroy", () => { observer.disconnect() }) }, } </script> <style> .app-img { display: inline-block; } </style>
Alright, our image starts on the page as a transparent PNG, and when it enters the viewport, it loads the real image. The next thing we need to make it better some placeholder while it waits to load.
We’ll add two props for the placeholder so it can either be a background color or a different (tiny) image. We’ll also add the placeholder as a <div>
which will be absolutely positioned over the entire component.
We need to know the size of the original image so that we can stretch our placeholder to the same size. If we don’t know the width and height (we’ll cheat and use the dataUrl
computed prop), we just won’t show the placeholder:
<template> <div class=" app-img "> <div v-if="dataUrl" :style="{ background }" class=" app-img__placeholder " > <img :src="placeholder || dataUrl" alt="" v-bind="$attrs" /> </div> <img :src="dataUrl" :alt="$attrs.alt || ''" v-bind="$attrs" class=" app-img__img " /> </div> </template> <script> export default { inheritAttrs: false, props: { src: { type: String, required: true, }, placeholder: String, background: String, }, computed: { dataUrl() { const { width, height } = this.$attrs if (!width || !height) return "" // create a tiny png with matching aspect ratio as img const w = 100 const canvas = document.createElement("canvas") canvas.width = w canvas.height = (height / width) * w return canvas.toDataURL() }, }, mounted() { const { src, $el } = this const observer = new IntersectionObserver(([entry]) => { const img = $el.querySelector(`.app-img__img`) const placeholder = $el.querySelector(`.app-img__placeholder`) img.onload = function() { delete img.onload if (placeholder) { placeholder.remove() } } if (entry.isIntersecting) { // Element is in viewport img.src = src observer.disconnect() } }) observer.observe($el) this.$once("hook:beforeDestroy", () => { observer.disconnect() }) }, } </script> <style> .app-img { display: inline-block; position: relative; } .app-img__placeholder { position: absolute; } </style>
A couple of other things to note are the in the intersectionObserver
. Once the main image has loaded, we want to remove the placeholder.
Theres a few more things we can do to make it a better experience.
We’ll accomplish most of this with CSS, but we do need one class added to the image once it has finished loading. And since we have a CSS transition, we also set a timeout to remove the placeholder. Any time we set a timeout, we also want to make sure we clear it when the component is destroyed.
For more Information and to build the website using Vue.js, Hire Vue.js Developer from us as we give you a high-quality product by utilizing all the latest tools and advanced technology. E-mail us any clock at – hello@hkinfosoft.com or Skype us: “hkinfosoft“.
To develop the custom website using Vue.js, please visit our technology page.
Content Source:
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
57 Sherway St,
Stoney Creek, ON
L8J 0J3
606, Suvas Scala,
S P Ring Road, Nikol,
Ahmedabad 380049
1131 Baycrest Drive,
Wesley Chapel,
FL 33544
© 2025 — HK Infosoft. All Rights Reserved.
© 2025 — HK Infosoft. All Rights Reserved.
T&C | Privacy Policy | Sitemap