Invalid Object & Array Manipulations in Vue.js 2

Objects

This is how you would usually set delete/add/set properties in Javascript. But Vue.js 2 can’t detect the changes if the object is manipulated in this fashion.
For it to be able to detect these changes, use the following.

or

Arrays

Similarly for arrays, if we use the following, then Vue.js 2 fails to detect the changes in state.

You will have to use the following commands to be able to deal with the above situation and many others.
Vue.js 2 has wrapped methods to help us create work arounds for such issues.

Wrapped methods

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

async & await in ES2017/ES8

async

Adding an async keyword to a function makes it asynchronous as the name itself suggests and it also return a promise instead of the value. We can define an ES6 function as async using the following syntax. This works with the old function syntax as well.

await

The await keyword can only be used inside an async function. When used, while calling an async function, it resolved the promise and returns the value.
The above code can be made more readable, by using the await keyword.

Here is a live example of asynchronous functions in action. Although the first function is called first, we don’t have to wait until the promise is resolved to a result by await, instead we can see rest of the functions calls and their promises being resolved earlier.
Code

Output

Demo

Sequential calls vs Parallel calls

The following is an example of sequential asynchronous function calls

If you want to make asynchronous function calls simultaneously, then you could use Promise.all and supply it with an array of asynchronous functions and then use await to return the result after all the calls are made.

ES2016/ES7 in 5 Minutes

The ECMAScript 2016 has just two small changes.

Array.prototype.includes()

Return type: boolean

Usage

Output

Demo

This replaces the array.indexOf(element) which returns the index if the element is found or -1 if it isnt. This new function allows you to check for NaN (Not a Number) and this works on objects in a array too, but they must match the instance being passed.

The Exponentiation Operator (**)

Usage

Output

Demo

This replaces the Math.pow(3, 2) function. This new operator allows for infix notation.

Vuex with vue-router and Bootstrap/jQuery

This post talks about using the vue-router (official router for Vue.js 2) alongside Vuex (state management pattern + library).

Using Vuex, gives you the ability to debug code easily, and switch between states in your chrome browser. For this you will need to install the Vue.js devtools chrome extension, and open the dev-tools in a page that uses Vue.js and then navigate to the Vue tab and choose the Vuex icon (usually 2nd from left).

In the following code, the ability to add/delete widget objects is implemented using mutations in Vuex. Here mutations are synchronous calls that can alter the state. This state can be easily accessed through the mapGetters in Vuex. Following this pattern keeps the state management pretty clean in larger applications, where multiple parts of the applications get to access/alter the state.

Note: You can also make asynchronous calls using actions in Vuex but, that part has not been included in the following code.

I have used bootstrap for quick styling. The router is setup with the widgets view as default. This code was built using the default vue-cli webpack template, which makes life easier for running unit tests, end to end tests and also building production ready code.

vuejs 2.0

This is the default view of the demo application. Below you can view the debugging capabilities of Vuex.

vuex

Code (github)

Learn Angular CLI in 5 minutes

Install

Make sure you have node and npm installed and that they are available via the PATH variable on Windows.

Create a new application

This following command will create a new application called collegestash in your current directory.
This does npm install too by default. Here the –routing flag tells it to create a router and add it to the project. The –style scss also specifies that this project will be using scss (Saas) instead of css for styling.

If you would like to be careful before you execute a command you can supply the -d flag which indicates a dry-run flag. The changes will not be written to disk, but you will be able to see the changes it will make in case the dry-run flag isn’t supplied.

or

This generates a component called login in a separate folder.

Service

or

This generates a service called login but doesn’t add the provider, and generates it in the main folder. You need to specify –flat false to generate this in it’s own folder. You can also the module in which you would like to include this by using the -m flag.

If you know the folder where you would like to place the service. Then you could do the following to put it in a specific folder.

Classes, Interfaces & enums

Generate typescript classes, interfaces and enums.

Pipes

Generate a pipe.

Modules

The following command generates a module called login in it’s own folder by default. No spec file is generated by default, hence we need to specify explicitly. You need to manually add this to your app.module to make sure they are linked together. Extra routing module gets created along with the required module.

Guard

Generate a guard for routing.

Build

This should build the application and output the files in build bundles with webpack runtime, app code, polyfills, styles, angular and other vendor files. You can supply the –prod flag to make sure the app is ready for production.

To be able to view sources, install the following and run the next command.

ng build

Build Environment vs Build Target

Build Environment – Choosing an Environment
Build Target – Refers to choosing whether or not to optimize.

Serve

This serves the app and opens it in your default browser.

Add External Libraries

You can use the angular-cli.json file and add them to styles and scripts arrays.

Eject

You can get away from the angular-cli dependency in the project.

Unit Tests

Runs all unit tests in the project, namely *.spec.ts files. Watches for changes and re runs them. So if you open this in a new terminal then this will, automatically detect the changes you make in the other terminal to the files in the project.

Setting the single run flag, can be best for use in Continuous Integration.
(or)

Setting watch to false gets the same result as above.

The above command is for code coverage which is in the coverage folder by default unless something different is specified in the angular-cli.json file.

End to end Testing

This runs the end to end tests.

Merge 2 sorted Arrays Inplace (JavaScript)

Time complexity: O(n)
Here n represents the sum of the lengths of both the arrays.

Code

Output

Demo

How to fix ng-if error in AngularJS

The ng-if directive has it’s own scope, so if you have issues with why a certain component is added or removed from the DOM even though your condition is true. It is probably because you aren’t referring to the right property. So this is how that can be fixed easily by referring to the parent scope.

User Registration Form using PHP 7.1.5

github

The first step would be to create a new MySQL database and then add a user with all privileges except GRANT. Now replace the values in the file db_connection.php with those.

Now once you are done with this run the file createTables.php from the browser. You should see a success message. If not make sure you have entered the right credentials and that MySQL server is running.

Now, if you don’t have a registration form UI (HTML5+js) then you can use postman from the chrome web store or any other testing tool.

You can use the following JSON to post to userRegistration.php

This should give you a success message when executed once and you should see the row added to your database in your PhpMyAdmin. If executed more than once, then you will get a message “User already exists”.

Note: Make sure that you have PHP 7.1.5 installed. This program works on HHVM as well.

How to Automate your Releases using only git & crontab?

You can easily automate your code deployment using crontab and git.
Lets assume you push your code to your remote PROD branch and a cronjob on prod keeps running or runs at a certain time checks if your branch is behind the remote or not and if it is, then it pulls code and restarts your application.

To start off make sure you have both git and a git repository. If you do then you can skip to Automation, if not then start by installing git and initializing a git repository on your local. For Ubuntu, here is how,

Note: replace ‘https://github.com/user/repo.git‘ with your HTTPS git repo URL.
If you see an error that remote already exists then you can use the following to remove it and then add your new repository under the same name or you can add a new name

                                                          or

Automation

Replace ‘/your-path-to-git/project’ with the path to your git project.
replace ‘branch-name’ with the branch you want to automate.
Save this in a file called automate.sh.

Replace both the occurences of ‘branch-name’ with your required branch name and then save the code in a file named ‘pull_code.sh‘ in the same directory as the ‘automate.sh‘.

If you run the file using the following command then it should check for changes in the remote branch and pull them. Make sure to change ‘branch-name’ to whatever branch name you are using.

Make the two files executable by the user

 

Cronjob

The next step would be to create a cronjob for this using crontab.
Use the following command for that,

Then hit ‘i’ start editing using vi (Visual Editor – The default editor that comes with the UNIX operating system).

You can add your email in the MAILTO parameter.  But this works only if  you don’t have logging set, here we have set all the output and standard error output to null, so it won’t work. For the email functionality to work, you need to have the mail server setup for this.

To log all the output to a file, replace the job with the following.

After adding the above code to your crontab, use the following to write changes and quit the vi.
ESC‘ + ‘wq!

This job is set to run every minute. It should have already output some data into your logs. Just to be sure we can restart the cron service once after the changes are saved.

 

 

Handling Date objects in Javascript

Handling date objects in javascript can be very tricky at times. Here are few tricky scenarios.

Comparision with ‘===’

When you compare two date objects that contain the exact same time stamp using ‘===’, then this will not be true as two objects can only be equal if they refer to the same object.

Output

Demo

The solution to this, is to convert this to some other format like date.getTime() or date.getISOString(), etc. Here is the example implementation of that.

Output

Demo

Copying a Date Object

When you try to copy date objects like the following example, then both the variables refer to the same date objects and whatever changes you make on either of them reflects on the other, which is not the required outcome

Output

Demo

To solve this we need to create a new Date object while assigning the date to a new variable.

Output

Demo