Home Blog Page 49

How to use nodejs date-fns Date javascript library

0
nodejs date-fns
nodejs date-fns

Hi Guys, Welcome to Proto Coders Point. In this article, we’ll know about the date-fns JavaScript Library for using Dates.

date-fns is a Modern date utility JavaScript library

This is so lightweight and makes our life much easier. The first step is to install the package. Make sure you have Nodejs and IDE installed to work and practice this.

On that directory, run the command npm init and get started with the project.

Now let’s install date-fns

npm install date-fns

Create a javascript file naming according to you. I’ll name it Dates.js

Now we’re ready to go ahead into the package and use it effectively.

Let’s start with Formatting Dates

One of the basic usage. We use the format method here.

const { format } = require("date-fns");

console.log(format(new Date(), "dd-MM-yyyy"));
console.log(format(new Date(), "dd/MM/yyyy HH:mm:ss"));
console.log(format(new Date(), "PPPP"));
nodejs data format date-fns

You can find more formats here


formatDistance – get age using dob

This helps in the comparison of dates and returns the gap value between the two dates. The program below will find your age!

How to find my age using date of birth

const { formatDistance } = require("date-fns");

const birthday = new Date("2004, 06, 13");
const presentDay = new Date();

console.log(`Age: ${formatDistance(presentDay, birthday)}`);
nodejs get age using dob using date-fns module

addDays

Add the defined years, months, weeks, days, hours, minutes, and seconds to the given date.

The method addDays is used to set up a deadline that is after a few days.

Simply, we can add days to any date to get the date of the day after some or a few days. It has many applications.

const { format, addDays } = require("date-fns");

const today = new Date();

// birthday after 6 days
const birthday = addDays(today, 6);

console.log(format(today, "PPPP"));
console.log(format(birthday, "PPPP"));
date-fns all days

Invalid Dates

Some of the dates aren’t valid when you execute them for eg:- 30th February which is not a date mentioned in any year. So how do we check if the provided date is valid or not? Here we have a method for that too. We use isValid, It returns false if the argument is Invalid Date and true otherwise.

const { isValid } = require("date-fns");

console.log(isValid(new Date("2021, 02, 30")));
nodejs check if data is valid or invalid
nodejs check if data is valid or invalid

To switch this invalid behavior we have a parse method. This method parses the date that you have given and returns accurate results.

const { isValid, parse } = require("date-fns");

const invalidDate = parse("30.02.2021", "dd.MM.yyyy", new Date());
const validDate = parse("25.03.2021", "dd.MM.yyyy", new Date());

console.log(isValid(invalidDate));
console.log(isValid(validDate));

The above code won’t give us 30th February, it will print 1st March 2021.


Now, Let’s learn about some common helpers

isAfter – Tells you Is the first date after the second one?

// Is 21 January 2022 after 23 December 2021?
var result = isAfter(new Date(2022, 1, 21), new Date(2021, 12, 23))
//=> true

isBefore – Is the first date before the second one?

// Is 21 January 2022 after 23 December 2021?

var result = isAfter(new Date(2022, 1, 21), new Date(2021, 12, 23))

// result => false

isDate – Returns true if the given value is an instance of Date. The function works for dates transferred across iframes.

// For some value:
const result = isDate('2022-02-31')
//=> false

isEqual – Are the given dates equal?

// Are 21 Jan 2021 06:30:45.000 and 21 Jan 2021 06:30:45.500 equal?
var result = isEqual(
  new Date(2014, 6, 2, 6, 30, 45, 0),
  new Date(2014, 6, 2, 6, 30, 45, 500)
)
//=> false

Conclusion

We can’t talk about each and every method here, it takes days to learn about. But as you build projects, you can have a look at methods that you find useful in your problem. You’ve learned the essential methods here. Search the specific usage in its documentation.

How does MERN Stack Works

0

Hi Guys, Welcome to Proto Coders Point. In this article, we’ll know about What MERN stack is and how it works!

The MERN Stack stands for MongoDB, Express JS, React JS, Node JS. This is a full tech stack for building scalable web applications. MERN Stack developer is a full-stack developer who works on such technologies. Here’s the MERN stack meaning & full form

M for MongoDB

MongoDB: A NoSQL Database which is differentiated from a traditional relational database

Objects -> Collection -> Documents -> Data

We can use documents instead of designing a database with tables. MongoDB helps us to do this with its document model.

In Mongo, you can store well data structures with subtopics and fields being objects as well. MongoDB takes care of almost all the features. You can literally keep whatever you want into the collection and it’ll store it!

E for Express JS

Express: Web Server. Express, is a back-end web application framework for Node.js. It facilitates the fast development of Node-based Web applications.

Some of the core features of the Express framework −

  • Allows us to set up middlewares to respond to HTTP Requests.
  • Defines routes that are used to perform different actions based on HTTP Method and URL.
  • Allows rendering HTML Pages dynamically based on arguments passed to templates.

R for React JS

React – The front-end JavaScript library for building interactive user interfaces or UI components.

Reactjs designs simple views for each state and will efficiently update and then render the right components when your data switches.

N for Node JS

Node – Base Server. It is a back-end JavaScript Runtime environment that executes JavaScript code outside a web browser.

Integration – Putting it all together

The MERN architecture allows you to easily build an architecture (frontend, backend, database) entirely using JavaScript and JavaScript Object Notation.

Express.js and Node.js make up the middle tier of the application. Express.js is a server-side framework and Node.js is a famous and powerful JavaScript server platform. Regardless of which tech stack you choose, either MERN, MEAN, or MEVN is the ideal approach to working with JavaScript anyway.

Feasibility of four best technologies, i.e. MongoDB, Express JS, React JS, and Node JS.

Most popular tech stack in 2021 which enjoys the support of the biggest community of developers with so much support

Open Source Libraries and Framework.

Thanks for reading and I hope you learned something, share it with your connections and let them know about such a wonderful tech stack.

JavaScript Promises Explained – with Js Promise.all

0
JavaScript Promises

Hi Guys, Welcome to Proto Coders Point. In this article, we’ll learn about JavaScript Promises!

JavaScript is synchronous [single threaded] language.

While executing the code JavaScript runs from top to bottom, line by line so it is synchronous but we can change the behavior of JavaScript to asynchronous using some functions.

Why Promises?

Writing functions inside another function as an argument is known as callbacks. We use callbacks for breaking the tasks into small tasks but as we use callbacks a lot it turns into a callback hell.

So what’s the solution to this hell? – Promises – they are used to solve the callback hell problems and to handle our tasks in a better way.

Understanding Promises in javascript!

Syntax – Basic JS promises code

var promise = new Promise(function(resolve, reject) {
  const x = "ProtoCodersPoint";
  const y = "ProtoCodersPoint"
  if(x === y) {
    resolve();
  } else {
    reject();
  }
});
   
promise.
    then(function () {
        console.log('Success, You are a Coders');
    }).
    catch(function () {
        console.log('Some error has occurred');
    });

There are three kinds of Promises – Pending, Resolve and Reject, For eg – We have a pizza shop. According to that:-

  • Pending: The situation when customer is taking time to place an order of pizza, it’s pending
  • Resolve: The situation when customer has received pizza and he is happy
  • Reject: The situation when customer didn’t receive his order and left

.Then Handler

Use .then handler – It returns a promise when our actual promise was resolved.

.then(() => {})

You’re telling someone to first do this, then do this.

Promise Chaining

You keep writing .then(() => {}) and code does the tasks, one after the another. It is much effective than callback.

.then(() => {
    console.log("Pizza was ordered") 
})

.then(() => {
    console.log("Production has started") 
})

.then(() => {
    console.log("Pizza was delivered") 
})

Promises: Error Handling

Let’s catch our error. Suppose our Pizza Store is closed. So we’ll say

let storeOpen = false;

To Handle this, we use the .catch handler

Just like .then handler, it also returns a promise only when our actual promise is rejected.

Note: Make sure you have no code between your previous .then handler and .catch handler

.catch(() => {
  console.log("Customer Left")
})

.Finally Handler

It works when our promise is resolved or rejected, regardless of anything.

.finally(() => { 
    console.log("end of the day")
})

.then works when the promise is resolved.

.catch works when the promise is rejected.

.finally works when the promise is resolved or rejected

Now, We’ll look at how we can write promises in a better way to keep our code simple and clean using async & await.

Before:

function order(){
   return new Promise((resolve, reject) => {
 // Write code here})
}

After: using async/await

Just write the word async before any normal function & it becomes a promise.

async function order(){ // Write code here }

Try and Catch

try word is used to run our code

catch is used to catch our errors

Promises -> resolve, reject

Async/Await -> try, catch

async function kitchen(){
   try {
     await abc;
   } catch(error) {
     console.log("abc does not exist",error)
}
kitchen()  // run the code

Now, What is Await?

Await Keyword means waiting until the promise returns its result & settles.

Example:

We want to ask our customer which toppings would they love to have on their pizza?

So, the kitchen is stopped but another staff is working outside.

async function kitchen(){
 console.log("A Pizza")
 console.log("B Pizza")
 console.log("C Pizza")
 
 await toppings_choice()
 console.log("Chilli Flakes")
 console.log("Cheese")
}
// Trigger the function
kitchen();

console.log("Staff working outside")

We’re asking customers & till then, other works are done.

Once, we get the toppings chosen by the customer, we can enter the kitchen and finish the job.

While using Async/ Await, you can also use .then, .catch, .finally handlers because they also are a core part of promises.

All you need to know about Promise.all

Promise.all take asynchronous functions to the new level as it helps you in a grouping of promises.

The Promise.all() method accepts an emphasized object, such as an array of promises as a value, and returns a single promise that resolves to a resulting array of the input promises.

When all input promises have been resolved or the emphasized value does not contain a promise, the returned promise will be resolved.

It rejects straight away when a value promise rejects.

Where it is used?

It is mostly used when there are many asynchronous tasks happening that the overall code depends upon to work successfully – all the code that we want to run before we continue to execute the code.

const firstpromise = new Promise((resolve, reject) => {
  setTimeout(resolve, 200, "first promise resolved");
}); //will be resolved after 200ms

const secondpromise = 38; //non-promise

const thirdpromise = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, "second promise resolved");
}); // will be resolved after 100ms

Promise.all([firstpromise, secondpromise, thirdpromise])
  .then((values) => {
    console.log(values);
  })
  .catch((err) => {
    console.log(err);
});

//expected output: ['first promise resolved', 38, 'second promise resolved']

 If any of the promises fail or rejects, then all the remaining promises also fail. Then Promise.all get rejected.

Promise.allSettled()

Promise.allSettled() is much useful for performing independent async functions, and collecting the result of those operations.

It accepts a list of Promises and returns a new Promise that resolves after all the input Promises have been settled, resolved, or rejected.

JavaScript Promise.allSettled() example below:

var arr=[];

Promise.allSettled([A(),B(),C(),D()])
  .then((value)=>{
      for(var i of value){
          if(i.status=='fulfilled'){
            arr.push(i.value)
          }
          
      }
    
    console.log(arr);
}).catch(console.log);

function A(){
    return new Promise((resolve,reject)=>{
        resolve("A Solved"); 
    });  
}

function B(){
    return new Promise((resolve,reject)=>{
        resolve("B Solved");
   });  
}

function C(){
    return new Promise((resolve,reject)=>{
        resolve("C Solved");
   });  
}

function D(){
    return new Promise((resolve,reject)=>{
        reject("D Rejected");
   });  
}

The promise returned by Promise.allSettled()  fulfills an array, doesn’t matter if few or all input promises are rejected.

So this was all about understanding JavaScript Promises. Links to more resources for understanding this visually!

Is JavaScript Synchronous or Asynchronous?

What the Heck is a callback?

Understanding Promises in JavaScript – Part 1

Understanding Promises in JavaScript – Part 2

The Better way to write promises in JavaScript

I hope you liked this article. If you did, please like and share it.

7 Unknown Tools and Resources to Learn React.js

0
Tools and Resources to Learn React.js
Tools and Resources to Learn React.js

Hi Guys, Welcome to Proto Coders Point. In this article, we’ll see great React Tools, Developer Tools, and Resources.

React is being used for building a lot of apps. React is a JavaScript framework to make interactive UIs. It turns your code from JavaScript into HTML. We use JSX in React that looks like HTML but it isn’t.

Now because it is in high demand, everyone seems to be trying to find out amazing resources to learn it in a better way!

Here are a few amazing references that will facilitate you to get started with React:-

1. Egghead

https://egghead.io/courses/the-beginner-s-guide-to-react

Take free courses of React and build wonderful projects. Egghead gives you Beginner’s Guide to React!

Kent C. Dodds will tell you about what this course is about. There are 30 Lessons included.

2. React Bits

https://vasanthk.gitbooks.io/react-bits/content/

React Bits provides you with a compilation of React Patterns, techniques, tips, and tricks. Make your work effective with this. Some of the patterns are:-

  • Design Patterns – that include asynchronous nature, conditionals, dependencies, context, etc.
  • Anti Patterns – that include State & Props, Mixins, etc.
  • Handling UX Variations, Perf tips and Styling

3. React Cheatsheet

https://reactcheatsheet.com/

React Basics Cheat Sheet will help you get a more clear and great understanding of Reactjs in an organized way. Get Open source code for whatever you would like to build with links to documentation.

4. React Patterns

https://reactpatterns.com/

React Patterns will help you understand some topics of Reactjs, subscribe to them for daily updates. This includes Transitions, Elements, Components, Expressions, Props, etc.

5. Dev Community of Reactjs

https://dev.to/t/react

The official resource for Facebook’s React JavaScript library for building interactive and smooth user interfaces. The biggest community helps you when you’re facing any trouble in Reactjs. Also, tons of articles and blogs are being published on daily basis to help you learn more.

6. React Resources

https://reactresources.com/

Search for any type of resource you want to learn Reactjs. It can be in any form. It also helps you get version and components updates regarding React.js latest development, latest articles, and tutorials, etc.

7. Reactjs Official Documentations

https://reactjs.org/

This is the most important resource that contains the Official Documentation of the React JavaScript library by Facebook for building user interfaces. It is maintained by Reactjs Official Team.

In case you find any other amazing resources or websites, please be at liberty to share them with more readers in the comments section below.

Thank you for reading, bookmark it for later, and don’t forget to share with someone who needs this foremost.

Recommended Article

Different between react and angular

Learn Angular – Build first web app using angular

Flutter vs React native

7 best tools for react development

How to use bootstrap in React

How to create custom hooks in react

Flutter Salomon Bottom Navigation Bar

0
salomon bottom navigation bar
flutter salomon bar

Hi Guys, Welcome to Proto Coders Point. In this flutter article let’s create a bottom navigation bar in flutter, A another way of creating awesome & beautiful bottom navigation bar by using salomon bar package.

Let’s get started

Add Salomon bottom bar as library

1. Install

To Install salomon navigation bar, add it in pubspec.yaml under dependencies section.

dependencies:
  salomon_bottom_bar:

then hit pub get button or run flutter pub get.


2. Import salomon

To use it, any where within your flutter app you need to import salomon_bottom_bar.dart file.

import 'package:salomon_bottom_bar/salomon_bottom_bar.dart';


How to use salomon package in flutter for bottom navigation bar

Properties of salomon bottom bar

propertydescription
items:[]List of tab/ bottom bar in navigation.
currentIndex: 0Active bar
onTap:(position)used to navigate to pages
selectedItemColor:Color of active tab/bar.
unselectedItemColor:Color of inActive tab/bar.
duration:The animation duration while switching tabs at buttom.
curve:active tab/bar curve shape.
itemShape:Salomon Bottom Bar Item Active tab shape.

Syntax

bottomNavigationBar: SalomonBottomBar(
        currentIndex: _selectedTab,
        onTap: (position){
          setState(() {
            _selectedTab = position;
          });
        },
        items: [
         SalomonBottomBarItem(
             selectedColor: Colors.redAccent,
             title: const Text('Profile'),
             icon: const Icon(Icons.person)
          ),
          SalomonBottomBarItem(
              selectedColor: Colors.redAccent,
              title: const Text('Map'),
              icon: const Icon(Icons.map_outlined)
          ),
          ],
      ),

Complete Source Code

Flutter Salomon Bottom Navigation Bar

Output

main.dart

import 'package:flutter/material.dart';
import 'package:salomon_bottom_bar/salomon_bottom_bar.dart';

void main() async {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var _selectedTab = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text("Salomon Navigation Bar"),
          centerTitle: true,
        ),
      body: Center(
        child: Text('Flutter New Navigation Bar',style: TextStyle(fontSize: 20),),
      ),
      bottomNavigationBar: SalomonBottomBar(
        unselectedItemColor: Colors.deepPurple,
        currentIndex: _selectedTab,
        onTap: (position){
          setState(() {
            _selectedTab = position;
          });
        },
        items: [
         SalomonBottomBarItem(
             selectedColor: Colors.redAccent,
             title: const Text('Profile'),
             icon: const Icon(Icons.person)
          ),
          SalomonBottomBarItem(
              selectedColor: Colors.redAccent,
              title: const Text('Map'),
              icon: const Icon(Icons.map_outlined)
          ),
          SalomonBottomBarItem(
              selectedColor: Colors.redAccent,
              icon: const Icon(Icons.home),
              title: const Text("Home")
          ),
          SalomonBottomBarItem(
              selectedColor: Colors.redAccent,
              title: const Text('Chat'),
              icon: const Icon(Icons.chat_bubble_outline)
          ),
          SalomonBottomBarItem(
              selectedColor: Colors.redAccent,
              title: const Text('Search'),
              icon: const Icon(Icons.search)
          )
        ],
      ),
    );
  }
}

How to connect to AWS server instance using WinSCP

0
Connect to AWS Server using winSCP
Connect to AWS Server using winSCP

Hi Guys, Welcome to Proto Coders Point. In this Article we will checkout how to connect to amazon EC2 instance server using winSCP.

check out how to create aws server.


Connecting to AWS server instance

To establish connection to AWS server we need 2 software to be installed in our system.

  1. Putty – puttyGen – Will use it to convert file .pem to .ppk
  2. WinSCP – will use to get connected to aws server.

Make sure, both the software are installed.

Video Tutorial

start watching for time 4:00 if you have already created amazon compute instance.

How to Connect to AWS server using winSCP

firstly, you need to convert .pem file to .ppk.

note: .pem file will be provided to you when you create AWS Instance”

Secondly, connect to server using winscp.

Step 1: convert pem to ppk

.pem to .ppk can easily be converted by using putty generate.

  • open putty key generator.
  • click on load button.
  • browser to .pem file & select it.
  • then click on save private key.

Steps to convert .pem to .ppk – screenshot guide

Open putty gen

open puttygen

click on load button & browser to pem file


click on save private key & save ppk file



Step 2: Connect to AWS instance using winSCP

Here are the step to use winSCP to connect to AWS server using ppk file.

  1. open winSCP.
  2. click on new session.
  3. new Site: file protocal (SFTP) > Fill Host Name (ip address) > username (ubuntu).
  4. click on advanced button.
  5. SSH > Authentication > browser to the ppk file you have created.
  6. Login

Steps in Screenshot guide

open winscp > new Session

winscp new session

new Site: file protocal (SFTP) > Fill Host Name (ip address) > username (ubuntu).

winscp login

Advanced Button > SSH > Authentication > browser to the ppk file you have created.


click on login button


Therefore, you have successfully connected to AWS server using WinSCP.