Categories
javascript Uncategorized

Arrow Functions – When and When not to use them ?

Hey everyone 👋🏻,
In this article, let us understand When and when not should we use arrow functions.

Arrow Functions

With ES6, JavaScript has evolved a lot because of the customizations that the new standard brings to the language. It has immensely improved our development experienced with the introduction of Next Generation JavaScript features. One of such features that ES6 brings to the table is the Arrow Functions.
The purpose of writing this article is to make the reader aware about the scenarios where he/she should not use arrow functions and instead make use of the good old school function syntax or the function expression syntax. We need to be a bit careful as well while using arrow functions because they can affect the readability of our code as well.

When to use Arrow Functions ?

There are some solid reasons why using arrow functions can be a plus.

  1. Securing the scope : The arrow functions remember their context in which they are defined in and they stick to that.
    So even if we introduce a normal callback function and mix that with a couple of arrow functions, then that can lead to messing up of the scope.
  2. Compact : Easier to read and write. Just a fat arrow, and they can be anonymous as well.
  3. Code Clarity: When every function in your code is an arrow function, then a normal function is the one that we rely on for defining the scope. So we as developers can always look up the next higher order function statement to figure out the this keyword.

When not to use arrow functions ?

1. Defining methods on an object

In JavaScript, as we know a method is a function that we set in a property of the object. So right at the time of invoking the method, the this keyword points to the object that the method belongs to.

Now let us talk about Object Literals here. Let us say we want to define a method inside an object literal. At first, you might be tempted to use an arrow function for a method definition within the object literal. But let us understand with the help of an example, why you should not use an arrow function within the object literals.

const user = { 
  stocks : [
     {
      stock : 'Amazon', 
      price_in_dollars : 937,
      units_bought: 5
   },
   {
      stock : 'Tesla', 
      price_in_dollars : 652,
      units_bought: 3
   }, 
   {
      stock : 'Meta Platforms', 
      price_in_dollars : 465,
      units_bought: 2
   }
],
get_total_invested : () => { 
        console.log(this === window);
        return this.stocks.reduce((acc, stock) => acc + stock.price_in_dollars * stock.units_bought, 0);
  }
};

console.log(this === window);
const invested_amount = user.get_total_invested(); 
console.log(invested_amount); 

user.get_total_invested method as we can see is defined within an arrow function. But if you try the above code, the invocation to user.get_total_invested would throw a TypeError because in the above case this.stocks would resolved to undefined.

Image description

Now the thing to note here is that when we are invoking the get_total_invested method on the user object, the context in which it is called in is the window object which we can easily verify by comparing this keyword with the window object in the get_total_invested method as you can see within this method, the this keyword points to the window object. So in essence, this.stocks resolves to window.stocks and this ultimately gives us undefined because we don’t have any stocks property on the window object.

In order to solve this, we can simply switch to the function expression syntax or its shorthand for method definition. For this case, at the invocation point, this keyword would refer to the the thing to the left of the dot at the invocation point. Here is the code with the above modifications :

const user = { 
  stocks : [
     {
      stock : 'Amazon', 
      price_in_dollars : 937,
      units_bought: 5
   },
   {
      stock : 'Tesla', 
      price_in_dollars : 652,
      units_bought: 3
   }, 
   {
      stock : 'Meta Platforms', 
      price_in_dollars : 465,
      units_bought: 2
   }
],
get_total_invested(){ 
        console.log(this === user);
        return this.stocks.reduce((acc, stock) => acc + stock.price_in_dollars * stock.units_bought, 0);
  }
};

const invested_amount = user.get_total_invested(); 
console.log(invested_amount);

Now in the above code, get_total_invested is a method that is being called on the user object. So with the regular function syntax, the thing to the left of dot which is the user object here is what this resolves to in the end and therefore the above code would work fine. Here is the output for the above code :

Image description

From the output, you can also easily decipher that the this keyword indeed points to the user object and hence this === user returns true as a result.

Let us now move forward and take arrow functions with Object Prototype

function User(name, age, profession) { 
  this.name = name; 
  this.age = age; 
  this.profession = profession;
}
User.prototype.sayHello = () => { 
  console.log(this === window);
  return `Hello ${this.name}`; 
}
const user = new User('Alex',24,'Developer');
console.log(user.sayHello());

Now here also the same thing holds true as discussed above. In the above code, instead of using the arrow function syntax for defining our sayHello method where the this keyword points to window we should instead use the function expression syntax to solve this. So here is the modified code :

function User(name, age, profession) { 
  this.name = name; 
  this.age = age; 
  this.profession = profession;
}
User.prototype.sayHello = function(){ 
  console.log(this === window);
  return `Hello ${this.name}`; 
}
const user = new User('Alex',24,'Developer');
console.log(user.sayHello());

So with just this simple change, sayHello regular function is changing its context to user object when called as a method : user.sayHello().

2. Arrow Functions cannot be used as constructors

For constructors, use regular functions otherwise JavaScript will throw an error if it encounters an arrow function getting used as a constructor. This means that JavaScript implicitly prevents from doing that by throwing an exception.

Let us go a bit deeper inside and try to understand a bit more on this :

In simple words, the objects (or the “constructors”) rely on the this keyword to be able to be able to be modified.

The this keyword always references the global object which is the window object.

So if we have something like this :

const User = (name, age, profession) => { 
    this.name = name; 
    this.age = age;
    this.profession = profession; 
}
const user = new User("Alex", 21, "developer"); 

Executing new User("Alex", 21, "developer"), where User is an arrow function, JavaScript throws a TypeError that User cannot be used as a constructor.

But, instead if you do something like this :

const User = function(name, age, profession) {
   this.name = name;
   this.age = age;
   this.profession = profession; 
}
const user = new User('Alex',21,'developer');
console.log(user.name);

Now here, the new keyword does some magic under the hood and makes the this keyword that is inside the User to initially first refer to the empty object instead of referencing to the global object like it earlier did. Right after this, new properties like name,age and gender get created inside this empty object pointed to by the this keyword and the values will be Alex,21 and developer respectively. Finally, the object pointed to by the this keyword gets returned.

Now a thing to note here is that arrow functions do not allow their this object to be modified. Their this object is always the one from the scope where they were statically created. This is called Static Lexical Scope. This is precisely the reason that why we cannot do operations like bindapply, or call with arrow functions. Simply, their this is locked to the value of the this of the scope where they were created.

3. Arrow Functions as callback functions

As we know in client side JavaScript, attaching event listeners to the DOM elements is a very common task. An event triggers the handler function with this as the target element.

So for example, let us say we have this code 

const button = document.querySelector('button');
button.addEventListener('click',() => { 
 console.log(this === window); 
 this.innerHTML = 'Changed';
});

Now as discussed just a while back, this points to the window object in an arrow function that is defined in the global context. So whenever a click event occurs, browser tries to execute the handler function with the button as context, but arrow functions still stays bound to its pre-defined context.
In above code, this.innerHTML is same as window.innerHTML which does nothing infact.

In order to solve this, we need to make use of the function expression syntax which will allow us to change this depending on the target element.

const button = document.querySelector('button');
button.addEventListener('click', function() { 
 console.log(this === button); 
 this.innerHTML = 'Changed';
});

Now for the above code, this keyword will infact point to the button. Therefore, this.innerHTML will correctly modify the button text and reflect the same in the UI.

So this is it for this article. Thanks for reading.

Categories
backend javascript nodejs

How Authentication works in REST APIs ?

Hey everyone 👋🏻,

In this article, let us learn about more about REST APIs. This is the second article on the topic REST API. The first article on this topic can be read by clicking on the below link :

https://dev.to/thenerdydev/what-is-a-rest-api-288l

How authentication works in REST API ?

Alt Text

So we again have our client and server. The client in order to authenticate needs to first send the authentication data (credentials), so basically the email and the password. This password is then compared with the password that is kept in the database before granting the access to the user. Now if you are working with an Express based server, then you must have used a package called bcryptjs that helps with all of this stuff. In traditional applications, we used to check data on the server and if the data was valid and if it was valid, only then a session used to get established.

Why no sessions any more ?

Well, there is a reason for this. We do not use session any more because REST APIs are stateless. The client and the server do not share the same connection history which means that both are totally decoupled from each other. Here we don’t care about the clients. Every request is treated as standalone which means that every request should have all the data it needs to authenticate itself. With session, the server has to store the information about the client that it is authenticated and this is not how REST APIs work. Therefore this approach is not what we use nowadays.

Now here in this approach we will still check the validity of the email and password combination on the server. But contrary to what we do in case of sessions, here we return a token to the client and that token is something that gets generated on the server. This token would hold some information that can be validated by the server and this token will then be stored in the client so basically in the local storage of the browser. The client can then attach this token to every subsequent request it sents to the server. Stored token is sent to authorize subsequent request and targets the resource on the server which requires authentication.
That token can only be validated by the server who created that token.

Now what if you try to change or fake the token ?

If you try to change or fake the token on the client side, then that will be detected because the server uses a special algorithm to generate the token and you simply cannot fake it since the algorithm that uses to generate the private key is not known to you.

What’s that token ?

JSON data + Signature => => => JSON web token (JWT)

This JWT (json web token) is what gets returned to the client and the signature can only be verified by the server. So you cannot edit or tamper the token at the client because the server will detect and will invalidate the token. This is how authentication is done in REST APIs.
So in essence, we have a token which can be checked by the server but need not be stored by the server.

So generating the token is one thing, the server sends the token. Next we need to make sure that we can send the token back to the server/backend REST API and then we check for the existence and the validity of token before we allow the request to continue.

If no token is attached to the incoming request, we should simply block access to those routes which do require some form of proven authentication. Remember, it is for the private routes that you do need a token attached to the request so that the user can access them.

Now to basically append the token with request you could attach the token with query params of the url or you could send them inside the body of NON-GET requests. But the best solution would be to send the token along with the headers. The benefit of this is that this would keep your URL clean. Also headers makes a lot of sense for the meta information which our token is in the end.

Now with Express.js, we use the jsonwebtoken package for decoding and verifying our token on the backend.

We use jsonwebtoken.verify to both encode and verify the token on the backend. We can also use jsonwebtoken.decode at the server side as well but then it won’t verify the token there.

Wrap up

The REST API server doesn’t care about the client. Requests are handled in isolation which means that every request is treated as if it arrived for the first time. So here we don’t use sessions. The REST APIs does not store any sessions. They don’t store any client data.

Due to no involvement of sessions in REST APIs, authentication works a bit differently here. Each request needs to be able to send some data that proves the authenticity of that request. JSON Web Tokens are a common way of storing authentication information on the client and proving the authentication status.

JWTs are signed by the server and can only be validated by the server.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text
Categories
frontend javascript reactjs

When to use the useRef hook ?

Hey everyone 👋🏻,

In this article, let us learn about a very special React Hook called as the useRef hook and understand how and when to use it.

What is the useRef hook ?

useRef hook is something that I briefly discussed in one of my articles where I described useRef hook as something equivalent to

Removing the state updating function from the useState, so basically just extracting the piece of state and take away the ability of state updation. This is something that will be equivalent to the useRef hook. I also discussed in that article that both the ref and state values persists across renders, so it is not the case that on every subsequent re-render they get set back to some default. So do make a note of the above points.

useRef is a React Hook which accepts a single argument as the initial default value and gives us something called as a ref. A ref is kind of an object that has a property called as current.

Let us see an example :

function SomeComponent() { 

    const usernameRef = React.useRef(''); 
    const handleSomething = () => { 
       console.log(usernameRef.currrent); 
       usernameRef.current = someOtherValue; 
    }
}

Now the things to note here is that usernameRef.current is used to access the value of the ref and if we want to update the ref value, then we can simply do so by setting usernameRef.current to a value of our choice.

To know more about refs, check my existing article on useRef hook. Here is the link for the same :

Image description

https://dev.to/thenerdydev/useref-hook-useref-vs-usestate-3i7k

In the above article, I have also taken some examples where I have demonstrated the usage of the useRef hook, we have discussed :

1. Ref Example – 1 (An Interval Timer)
2. Ref Example – 2 (Working with DOM using refs)
3. The third thing that we discussed in that article was :

useRef just like useState persists a value across renders but unlike useState it does not trigger a re-render of the component.

So in essence,

useRef = useState – state updating function

If you don’t know about the useState, no worries. You can learn about the same in this article :

https://dev.to/thenerdydev/react-hooks-demystifying-the-usestate-hook-in-under-10-minutes-examples-video-29ab

Let’s sum up what we learnt :

A ref is a plain JavaScript Object
{ current: <some_value> }

If you want to create a ref with the current value as null, then you can also make use of the createRef method,
React.createRef()

This gives us :
{ current: null }

Next, useRef(someInitialValue) also gives us a ref { current: someInitialValue }. The interesting thing about useRef is that it memoizes this ref so that it stays persistent across multiple renders of the component.

Another point to make a note of is that :

useRef(null) is basically equivalent to useState(React.createRef())[0]
But this kind of abuses the functionality.

Lastly, we learnt that useState causes a re-render in contrast to useRef. The state and the ref values (both) persist across re-renders.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Categories
frontend javascript

5 Frontend Development Trends to follow in 2022

Hey everyone 👋🏻,

In this article, let us discuss about Top 5 Frontend Development Trends to follow in 2022

1. JavaScript

JavaScript is one of the most popular programming languages that you can learn these days. More than 70 percent of the websites are developed using JavaScript. It is continually evolving as more and more features are getting introduced into the language. JavaScript is the language that powers the web and is one of the top most tools that big companies are using these days.

There are currently 1.4 million JavaScript libraries that can be used by web developers across the world. In addition, web browsers now feature a separate JavaScript engine that speeds up these computations, resulting in faster page load times. JavaScript is a constant trend in front end development with a plethora of libraries.

Image description
Source

2. JAM Stack

JAM Stack is not a technology or language but an architectural design that uses JavaScript, APIs, and Markup. These individual technologies can be combined to produce a decoupled web application whose front-end and back-end are separated. JAM Stack boasts of providing following benefits to websites and project workflows : Security, Scale, Performance, Maintenance, Portability and Developer Experience

Image description
Check the website : https://jamstack.org

3. Micro-frontends

Image description

The term Micro Frontends first came up in ThoughtWorks Technology Radar at the end of 2016. It extends the concepts of micro services to the frontend world. The current trend is to build a feature-rich and powerful browser application, aka single page app, which sits on top of a micro service architecture. Over time the frontend layer, often developed by a separate team, grows and gets more difficult to maintain. That’s what we call a Frontend Monolith.

The idea behind Micro Frontends is to think about a website or web app as a composition of features which are owned by independent teams. Each team has a distinct area of business or mission it cares about and specialises in. A team is cross functional and develops its features end-to-end, from database to user interface.

Source

4. React.js

Image description

React.js is one of the most popular JavaScript libraries for building modern and sleek user interfaces these days. It does not need an introduction as such because it is that popular that almost every new developer these days is learning React. React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes.

Image description
Source : https://www.npmtrends.com/react-vs-vue-vs-@angular/core

5. Progressive Web Applications

Image description

The idea behind Progressive Web Applications is to provide a native app experience to the user through the browser itself. PWAs are extremely beneficial as they are of lesser size (in KBs) and provide a near-similar experience like a native application. You would often see PWAs are released as “Lite” versions on the play store and do not exceed 1 MB in size. Even though it looks like a native app, it opens up a browser inside to view the items.

Progressive Web Apps (PWAs) are web apps that use service workers, manifests, and other web-platform features in combination with progressive enhancement to give users an experience on par with native apps.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text
Categories
frontend javascript vuejs

✨8 Vue Projects Every Beginner Should Try

Hey everyone 👋🏻,

In this article, let us see 8 Vue Projects Every Beginner Should Try.

This article was first published on https://the-nerdy-dev.com/.
Check the website for more interesting articles and tutorials on Web Development.

Introduction

Image description

Vue.js is an open-source model–view–view-model (MVVM) front end JavaScript framework for building user interfaces and single-page applications. It was created by Evan You, and is maintained by him and the rest of the active core team members

1. 6 Hours Vue.js and Firebase Project – FireBlogs by @traversymedia

Learn how to build a multi-user blog project with Vue.js, Vuex and Firebase.

What will you learn?

  1. Vue.js basics and fundmentals
  2. State Management using Vuex
  3. Working with Firebase

2. Build a COVID Tracker App with Vue.js and Tailwind

In this project, Brad uses Vue.js and Tailwind to create a Simple COVID Tracker Application.

What will you learn?

  1. Vue.js Fundamentals and Basics
  2. Working with Tailwind.css

3. Vue.js + Vuetify + Firebase Project – DevMeetup

In this tutorial, Maximilian Schwarzmuller shows how to build a complete Project – a Developer Meetup App – with Vue.js 2, Vuetify and Firebase. This is a 24 part series.

Image description

www.youtube.com/playlist?list=PL55RiY5tL51qxUbODJG9cgrsVd7ZHbPrt

What will you learn?

  1. Vue.js 2 Fundamentals and Basics
  2. Vuetify Components
  3. Working with Firebase

4. Build a Weather App in VueJS | Vue Beginner Tutorial

Learn how to make a Weather app in Vue JS, we use the Open Weather Map API to make calls to a restful api to return the current weather data. This uses the Modern Javascript Fetch API along with Vue JS Methods and conditionals.

What will you learn?

  1. Vue.js basics and fundamentals
  2. Interacting with APIs via API calls.

5. Build a Invoice App With Vue 3, Vuex & Firebase

In this video, we build out a full CRUD (create, read, update & delete) invoice app using Vue 3, Vuex & Firebase.

What will you learn?

  1. Vue.js basics and fundamentals
  2. Working with Firebase
  3. State Management using Vuex

6. Create a Gridsome Portfolio – Vue.js project

Learn how to make a portfolio kind of an application using Gridsome library with Vue.js

What will you learn?

  1. Vue.js basics and fundamentals
  2. Gridsome library

7. E-commerce Website With Django and Vue Tutorial (Django Rest Framework)

Learn how to build an e-commerce website using Django and Vue from scratch. Django uses Python Vue uses JavaScript.

Django Rest Framework is used to build the API and backend.
The frontend is a separate Vue project. To handle the payments, we implement Stripe.

What will you learn?

  1. Vue.js basics and fundamentals
  2. Learn Django to create a full stack application

8. Full Stack Web App in Vue.js & Express.js

Image description
Learn how to build a full stack application using Vue.js and Express.js with Postgres as the database

What will you learn?

  1. Vue basics and fundamentals
  2. Making a full stack application with Vue.js and Express along with Postgres as the database

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

👉🏻 Follow me on Twitter : https://twitter.com/The_Nerdy_Dev
👉🏻 Join our Discord Server : https://discord.gg/fgbtN2a

Categories
backend javascript

Backend Developer Roadmap (2021)

Hey guys 👋🏻,
In this article, let us understand the roadmap that will help you in becoming a Backend Developer in 2021.

Every website that we build these days need a backend to manage the business logic of the application. To manage huge data for an application you need a database along with a API that makes the interaction between the client and the backend possible. Then there are other aspects to it that you need to care about when your application scales.

Image description

So without a further ado, let us first go over the technologies and skills that you need to succeed as a backend developer.

As a pre-requisite, you do need the knowledge of:

  1. Internet and How the Web Works
  2. Operating Systems
  3. Frontend Knowledge is a plus
  4. Some programming experience is also a plus though it can be learned along the way.

Needless to say if you want to succeed as a backend developer, you must have some programming knowledge under your belt. You do need to improve your coding skills if you are just getting started. For starters, getting familiar with the constructs of programming is important. A language like Java would be good to get you started with programming. You can also go for other languages like JavaScript, Ruby, Python etc.

Some of the prominent backend technologies are :

  1. Golang
  2. Node.js
Image description
  1. Ruby on Rails
Image description
  1. Django
Image description

and more…

Next comes the knowledge of version control system, also called as VCS. Now this enables developers to collaborate and work on a project along with that it also also allows us to manage the versions by recording the snapshots of the project history and even allow us to backtrack if a wrong change was committed. This way it limits the risk of errors and provides an efficient workflow to collaborate on projects.

For backend development, you can use the following version control systems.

Image description
  1. Git
  2. GitHub
  3. GitLab
  4. BitBucket

Database

Next you need the knowledge of a database :

Image description

A database as we know is an organized collection of data which can be structured or unstructured. The database caters to the storage aspect of our application. So it is responsible for storing the data of our application. We can also make queries against our database and retrieve the data in the form that we need.
Knowledge of databases is very important and a must have if you want to succeed as a backend developer.

Backend developers either use relational or NoSQL databases. Some of them are as follows:

Relational Databases

  1. PostgreSQL
  2. MySQL
  3. MS SQL
  4. Oracle
  5. MariaDB

NoSQL Databases

  1. MongoDB
  2. RethinkDB
  3. DynamoDB
  4. CouchDB
  5. ArangoDB
  6. Neo4J
    (to name a few)

Along with the knowledge of some of the databases described above, you will also need to be familiar with the basic database principles like :

ORMs, Transactions and Batches, ACID, Data Normalization, Indexing, Cursors etc.

APIs

Image description

APIs (Application Programming Interfaces) are a type of intermediate that allows services to communicate with one another. APIs are used by backend developers to connect different apps or services in order to give a better user experience on the frontend.

You should be aware of the following APIs:

  1. REST (important)

If you want to learn about REST APIs in detail, I do have an article on same :

  1. JSON
Image description
  1. SOAP
  2. GSON
  3. XML-RPC
  4. AES

Caching

Caching is the process of storing copies of files in a cache, or temporary storage location, so that they can be accessed more quickly. So essentially it is a technique for storing a copy of a resource in a cache (temporary storage location) so it can be accessed quickly without any delays (basically for fast access). The main goal of caching is to improve data retrieval performance while reducing the need to contact the slow-to-process underlying storage layer.

Here is a list of caching techniques and tools you should be aware of.

  1. CDN
  2. Server Side
  3. Client-Side
  4. Redis

Testing

Backend Testing is a testing method that checks the server side or database of web applications or a software. Backend testing is also known as Database Testing. The data entered in the front end will be stored in the back-end database. Backend developers utilize the following testing methods:

  1. Integration Testing
  2. Unit Testing
  3. Functional Testing

I may cover more on Testing in a separate article.

Code Analysis Tools

Code analysis is the analysis of source code that is performed without actually executing programs. It involves the detection of vulnerabilities and functional errors in deployed or soon-to-be deployed software.

Some of the tools used for code analysis are:

  1. SonarLint
  2. JUnit
  3. JaCoCo
  4. PMD
  5. SonarQube
  6. Qualys
  7. Jenkins

Architectural Patterns

An architectural pattern is a reusable solution to repeated issues in software development within a given context. The following are some of the most regularly used architectural patterns:

  1. Monolithic
  2. SOA
  3. Microservices
  4. CQRS
  5. Event Sourcing
  6. Serverless

Message Broker

A message broker is a part of software that allows systems, apps, and services to communicate with one another. A message broker is a module that converts the server’s formal messaging protocol into the client’s formal messaging protocol (receiver). Here is a list of some of the message brokers.

  1. RabbitMQ
  2. Kafka
  3. Kinesis
  4. JBOSS messaging

Containerization

Image description

Containerization is the packaging of software code with all required components, such as frameworks, libraries, and other dependencies, in order to create services that are isolated from one another in a container. Backend developers use containerization to make it easier to move or execute containers depending of their infrastructure or environment.

Docker is one of the most commonly used containers that you should learn.

Design Patterns

In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design. Design patterns are used to represent some of the best practices adapted by experienced object-oriented software developers. The following is a list of different design patterns that you should be familiar of.

  1. Singleton
  2. Factory
  3. Observer
  4. Decorator
  5. Adapter
  6. Mediator
  7. Composite
  8. Facade
  9. Iterator
  10. Proxy

WebHook

Webhooks are automated messages sent from apps when something happens. They have a message—or payload—and are sent to a unique URL—essentially the app’s phone number or address. Webhooks are almost always faster than polling, and require less work on your end.

They’re much like SMS notifications

A webhook, often known as a reverse API, is a method for an app to give real-time data to other apps. Webhooks, unlike APIs, do not require a request to be sent after a response. Instead, webhooks provide data as soon as it becomes available, without the need for a request or specific callbacks. The webhook’s fundamental characteristic makes it useful for both users and providers.

WebSocket

WebSockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers.

The WebSocket API is a reducing technology that allows a two-way interactive communication session to be established between a user’s browser and a server. You can use this API to send messages to a server and obtain event-driven responses instead of asking the service. A WebSocket is a persistent link between a client and a server. It uses a TCP/IP socket connection to create a full-duplex, bi-directional communication channel over HTTP. Simply put, it’s a thin, lightweight layer over TCP that allows subprotocols to be used to lodge messages.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
javascript reactjs web development

React.js – How to use Refs in React.js

Using refs in React.js

Hey guys 👋🏻,
In this article, let us cover the topic of How to use Refs in React.js

Let us investigate why React.js, a library that keeps your code away from DOM manipulation, keeps its doors open for you to access. React rethinks a view as a result of a state of a component. It provides JSX, a syntactic sugar over JavaScript, to design the view layer and then modifies the DOM itself rather than giving the control to the developer.

Still, the React team provided escape routes and kept the library open for certain situations that go beyond the scope of what React is designed for.

Creating Refs

Refs are escape routes and it’s better to avoid them whenever possible. When we obtain a DOM element using ref and then later modify its attribute, we might enter into a conflict with React’s diff and update approach.

Let’s start with a simple component and grab a DOM element using ref, assuming that you already know how to set up a basic react app.

In the above piece of code, we are using a react hook useRef to create and initialize a variable called buttonRef. We then assign buttonRef to ref attribute on button JSX element.

Using React refs

As we discussed earlier in this article we are declaring views based on the state, and though we are still altering the state using functions, we are not in direct control of the DOM changes. But in a few use cases, it makes sense to introduce refs in your code.

Focus Control

To better understand the problem statement let’s storify the situation.

Alex is a software development intern at Metflix Inc. and his manager has given him the task of creating contact forms. The manager has asked him to focus on the first input element in the form when a modal is opened. Alex is confused about how he can achieve this in React.js. Let’s help Alex out.

The first thing we need to do is to get a reference to the input.

Next, when our modal loads, we imperatively call focus on our input ref.

Note: You need to access the element through the current property of the ref you declare.

Detect if an element is contained

Similarly, we would want to take an action in the app when an event is dispatched. Like close the modal when the user clicks outside of it.

Here, we are checking if the user click is out of the modalRef limit. If it is we are calling close() function from props to close the modal.

Integrating DOM-based libraries

Like React, there are other utilities and libraries outside its ecosystem that have been in use for years. To use such libraries, refs come in handy.

GreenSock library is a popular choice for animation examples. To use it, we need to send a DOM element to any of its methods.

Let’s go back to our modal and add some animation

Forwarding Refs

Refs are useful for specific actions. The examples shown are a little simpler than what we usually find in a real-life web application. We need to deal with complex components and we barely use plain HTML elements directly. It’s common to use a ref from one component in another component.

The issue now is that passing a ref to this component will return its instance, a React component reference, and not the input element we want to focus on like in our first example.

React provides forwardRef, which allows you to define internally what element the ref will point at.

Now, when a parent component passes a ref value, it’s going to obtain the input, which is helpful to avoid exposing the internals and properties of a component and breaking its encapsulation.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
javascript web development

Understanding Primitives and Reference Types in JavaScript

Hey guys 👋🏻,
In this article, let us cover the topic of Understanding Primitives and Reference Types in JavaScript.

Image description

Primitive value is stored directly in the location that the variable accesses. And the Reference values are objects that are stored in the heap. Reference value stored in the variable location is a pointer to a location in memory where the object is stored. This is something that I will demonstrate just a bit later. So stay with me.

Basic Primitive Types and Reference Types

JavaScript supports 5 primitive data types: number, string, Boolean, undefined, and null.

These types are referred to as primitive types because they are the basic building blocks from which more complex types can be built. Of these five, only number, string, and boolean are real data types in the sense of actually storing data.

Undefined and null are types that arise under special circumstances. The primitive type has a fixed size in memory. For example, a number occupies eight bytes of memory, and a boolean value can be represented with only one bit.

Contrary to this, reference types can be of any length. They don’t have a fixed size.

For primitives, they are always copied as a whole value whereas for reference types they are copied by reference.

For variables that hold values we only compare their values whereas in case of reference types like objects, it is not the case.

Consider this example :

Image description
Image description

The above log gives true because both a and b are referencing to the exact same memory location. So let us say the memory for the arrow was allocated at some memory address of say 4k. So a is a reference that will point to the array object that is sitting at memory address 4k. So if you then assign a to b like we do above, then we have a new reference that points to the exact same object in the memory. So therefore since both the references point to the exact same object in the memory that is why it gives true for the strictly equality comparison between a and b (for the above log).

But if I declare another array with the exact same content say c.

and then do this :

Image description

Then the above log will resolve to false because this new array will get allocated at a different memory location say 5k. So if we compare a and c using a strict equality comparison, then it will resolve to false because both the references a and c point to different memory locations namely 4k and 5k respectively and hence you get false.

Now consider example for primitives. For this case you just compare the values. So if we have :

and then we say :

Then for the above log we make sure that both the type and the value are equal for the things (primitives under comparison). Both are 3 and both are numbers so hence we get true for this.

Next if we say

This will resolve to false because 3 and 4 are not equal.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
backend frontend javascript web development

What, Why and How to Validate ?

Hey guys 👋🏻,
In this article, let us learn about validation in case of application and learn about What, Why and How to Validate ?.

What, Why and How to Validate ?

To ensure that the data that you work with is the data in correct format, you need validation for it.

Let us answer these questiions :

Why should we use validation ?

Why would you add data validation to your application ?

When we have a user interacting with our website we typically have forms in any web application that we build. The bigger your application is the more data you will need from your users at some point of time. So we have that form which the user of the website interacts with and in the end this form is submitted with the POST request.

Then a request to the backend is sent along with the form data.
On our backend, we typically interact with the database using our server side logic or we may typically write our data into a file using the fs core module of Node.js. But in the end we take that data we receive and want to store it. This is why the need for data validation and sanitization arises.

If a user in our application would try to login with something that is not a valid email address, we should not allow access to the user, so we should prevent the user from entering something incorrect and getting access for that.

This is where we want validation to kick in.

How to validate and provide a good user experience ?

Obviously we got a user entering some data onto the form (Form Input) and let us say a Node.js application running on the server. We got a couple of places where we can validate, for example, we can validate on the client side of our application.

So right before any request hits the server, we can write some JavaScript, that for example checks the input at every keystroke and checks the input whilst the user is working on the form and then you can display an error right in the browser and this can greatly enhance the user experience on the client side for us.

This type of validation is totally optional because the user can see that code, user can change the validation and user can disable the JavaScript in the browser.

👉🏻This is not the protection that can secure you against incorrect data being sent to the server. This is not a secure solution it just is there to improve the user experience thing, so just to render proper error messages.

So,

we will focus on Server Side Validation. This is what we do with Node.js. This code can’t be used by the user, the user cannot disable this validation code that we define on the server side because this happens on the server not in the browser and this is the crucial part where we need to have validation to filter out incorrect values and this is what we will focus on. This ensures that we work with valid data in our node application and if we do plan on storing it ultimately we do store correct data in our database. There is also built in validation which we can use in databases like Mongo. This can be last resort. If we have strong validation on the server side no invalid data will be able to reach the database because you already filtered the incorrect data in the server side validation.

Validation at database level is also optional.

You must have to validate at server side at all means. If the validation fails, you must have to return an error message in user interface with helpful message and do not reload the page with the user input intact with the correct error message rendered in our user interface. This is because reloading offers a horrible experience to the end user and this would clear up all your form data and you would have to enter all the data again !

Example – Discussion on Validation for a Registration Page :

Some common validations for validating the form controls of a registration page are these :

✔ Check for the correctness of the mail. It is according to the format (must not be in bad format). It also must possess @ symbol
✔ Password must be atleast 6 characters long.
✔ Password and ConfirmPassword fields must match.

etc. etc.

Please note
You are not just restricted to above validations, you could have other validations as well for your form controls.

If you want to perform validation for your APIs that you have written using Express, you can make use of packages like

1. Express Validator

Image description

Though you could also make use of another npm package which is Joi for performing validation.
2. Joi

Image description

Now typically we want to validate for NON-GET requests because generally these are the cases in which the user will send some data to the server.

Sanitizing user input

We can ensure as an example that there is no extra whitespace in the string that is passed by the user on the left or on the right
You can normalize the email that is converted to lowercase or things like that. There is a couple of things that you can ensure that the data you get back is valid but is also stored in the uniform way without any extra whitespace or anything like that.
This is what we mean by Sanitization.

Sanitizing input is also that makes sense to be done. For sanitizing the email we can make use of the normalizeEmail method that is available on express-validator

Image description
Similarly, for sanitizing the password we can make use of the trim method that is also provided to us by the express-validator

Sanitizing data is important to ensure that your data is stored in the uniform format.

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text

Categories
frontend javascript web development

My Top 3 Server Side Technologies. What are yours ?

Hey guys 👋🏻,
In this article, I will unveil My Top 3 Server Side Technologies that I work with.

Image description

Node.js

Image description

Node.js is a JavaScript Runtime for building scalable network applications. It is blazing fast and it is best to use when we have large number of concurrent connections active at a given point of time and requires immediate response time.

Django

Image description

Django is a backend development framework that provides you a lot of things out of the box (authentication system for example). It allows you to focus on building the application without re-inventing the wheel.

Ruby on Rails (ROR)

Image description
Ruby on Rails is just like Django which uses batteries included approach. It helps developers to build scalable applications because it abstracts and simplifies common repetitive tasks.

What are your Top 3 ? Let me know in the comments section

So this is it for this article. Thanks for reading.

If you enjoy my articles, consider following me on Twitter for more interesting stuff :

Image description

⚡Twitter : https://twitter.com/The_Nerdy_Dev

Don’t forget to leave a like if you loved the article. Also share it with your friends and colleagues.

Alt Text