Sunday, 7 April 2024

Error boundary React

 


A class component becomes an error boundary if it defines either (or both) of the lifecycle methods static getDerivedStateFromError() or componentDidCatch(). 

Use static getDerivedStateFromError() to render a fallback UI after an error has been thrown. Use componentDidCatch() to log error information.


example:


class ErrorBoundary extends React.Component {

  constructor(props) {

    super(props);

    this.state = { hasError: false };

  }


  static getDerivedStateFromError(error) {

    // Update state so the next render will show the fallback UI.

    return { hasError: true };

  }


  componentDidCatch(error, errorInfo) {

    // You can also log the error to an error reporting service

    logErrorToMyService(error, errorInfo);

  }


  render() {

    if (this.state.hasError) {

      // You can render any custom fallback UI

      return <h1>Something went wrong.</h1>;

    }


    return this.props.children; 

  }

}


<ErrorBoundary>

  <MyWidget />

</ErrorBoundary>

React Questions and awnsers

 Type of Components

Class(Statefull Components) - Error Handling mange session(Error Boundary), Life Cycle

Functional - Module Way -I will be little faster when use function (React hook , After react 16 Version)


Life Cycle

Mounting,Updating and Unmounting

Mounting

    constructor()

    getDerivedStateFromProps()

    render()

    componentDidMount()

Updating

    getDerivedStateFromProps()

    shouldComponentUpdate()

    render()

    getSnapshotBeforeUpdate()

    componentDidUpdate()

Unmounting

    componentWillUnmount()

React Hook

UseState,UseEffect,UseContext,UseRef,UseReducer,UseCallBack,UseMemo,Custom Hooks

UseState

useState accepts an initial state and returns two values:

The current state.

A function that updates the state.

UseEffect

useEffect runs on every render. That means that when the count changes, a render happens, which then triggers another effect.

API Using in React

Axios - Json by default

Axios has the ability to inercept HTTP Request

Axioshas built-in support for download progress

Fetch

Fetch by default ,Do not provide a way to intercept request

Fetch does not support uload progress

How to use transfer the one comp to another

Parent to child - using props

child to parent - using call back function

Monday, 12 February 2024

Lifetimes Dependency Injection

 There are 3 types of lifetimes supported by ASP.NET Core for the dependency injection,

1.Transient Service

2.Scoped Service

3.Singleton Service

Let’s have a look in depth at how it works


transient -each action one object will be create 

not the data will be passed

external utiltiy ofn previous t

scoped - keep the session through the request

registion reportiry 


shopping cart- scope

order it send the mail - transient (not need any data)

Sunday, 15 May 2022

React JS Comments

 Creating a new application

Create React App provides multiple ways to create React application.

Using npx script.

npx create-react-app <react-app-name>

npx create-react-app hello-react-app

Using npm package manager.

npm init react-app <react-app-name>

npm init react-app hello-react-app

Using yarn package manager.

yarn init react-app <react-app-name>

yarn init react-app hello-react-app

Selecting a template

Create React App creates React application using default template. Template refers the initial code with certain build-in functionality. There are hundreds of template with many advanced features are available in npm package server. Create React App allows the users to select the template through –template command line switch.

create-react-app my-app --template typescript

Installing a dependency

Using npm package manager.

npm install --save react-router-dom

Using yarn package manager.

yarn add react-router-dom


Running the application

React application can be started using npm or yarn command depending on the package manager used in the project.

Using npm package manager.

npm start

Using yarn package manager.

yarn start

To run the application in secure mode (HTTPS), set an environment variable, HTTPS and set it to true before starting the application. For example, in windows command prompt (cmd.exe), the below command set HTTPS and starts the application is HTTPS mode.

cmd

set HTTPS=true && npm start


npm start and  npm run are same further check with below link

https://docs.npmjs.com/cli/v8/commands/npm-run-script

Building

A single command is enough to create a production build of the application.

npm run build

> expense-manager@0.1.0 build path\to\expense-manager

> react-scripts build

Creating an optimized production build...

Compiled with warnings.

File sizes after gzip:

   41.69 KB   build\static\js\2.a164da11.chunk.js

    2.24 KB   build\static\js\main.de70a883.chunk.js

    1.4  KB   build\static\js\3.d8a9fc85.chunk.js

    1.17 KB   build\static\js\runtime-main.560bee6e.js

  493     B   build\static\css\main.e75e7bbe.chunk.css


The project was built assuming it is hosted at /.

You can control this with the homepage field in your package.json.

The build folder is ready to be deployed.

You may serve it with a static server:

   npm install -g serve

   serve -s build


Real DOM and Virtual DOM

 What is DOM?

“The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.”

The DOM is an abstraction of a page’s HTML structure. It takes HTML elements and wraps them in an object with a tree-structure — maintaining the parent/child relationships of those nested HTML elements. This provides an API that allows us to traverse nodes (HTML elements) and manipulate them in a number of ways — such as adding nodes, removing nodes, editing a node’s content, etc.


Real DOMVirtual DOM
DOM is a language-neutral interface allowing programs and scripts to dynamically access and update multiple objects like content, structure, and style of a document.Is a collection of modules designed to provide a declarative way to represent the DOM for an application.
The DOM represents the document as nodes and objects.A virtual DOM object is a representation of a DOM object, like a lightweight copy.
It is an object-oriented representation of a web page, modified with a scripting language like JavaScript.Virtual DOM is ideal for mobile-first applications.





How does updates work in React?

On the first load, ReactDOM.render() will create the Virtual DOM tree and real DOM tree.

As React works on Observable patterns, when any event(like key press, left click, api response, etc.) occurred, Virtual DOM tree nodes are notified for props change, If the properties used in that node are updated, the node is updated else left as it is.

React compares Virtual DOM with real DOM and updates real DOM. This process is called Reconciliation. React uses Diffing algorithm techniques of Reconciliation.

Updated real DOM is repainted on browser






Saturday, 8 May 2021

Select and delete in single statement in SQL

Below SQL Query , Is to get the data after deleted from the table.

It can be used in the store procedure , in scenario of getting the data and deleting the data for same. So that when procedure run the thread then it will not lead to error due to no data present in the table .

Same thing can be achieved in two separate query with example below.

Begin tran t1

Select * from contacts where Id=2

Delete from contacts where Id = 2

Commit tran t1

Below is the operation ,  done in single query instead of two query

Begin tran t1

Delete from 

Contacts

output

Deleted.id,

Deleted.Name,

Deleted.Address,

Deleted.Phone

where id =2

Commit tran t1




Saturday, 27 March 2021

Angular Hook Life Cycle

Angular Hook Life Cycle: 

1.ngOnChanges

2.ngOnInit

3.ngDoCheck

4.ngAfterContentInit

5.ngAfterContentChecked

6.ngAfterViewInit

7.ngAfterViewChecked

8.ngOnDestroy

ngOnChanges

ngOnChanges triggers following the modification of @Input bound class members. Data bound by the @Input() decorator come from an external source. When the external source alters that data in a detectable manner, it passes through the @Input property again.

With this update, ngOnChanges immediately fires. It also fires upon initialization of input data. The hook receives one optional parameter of type SimpleChanges. This value contains information on the changed input-bound properties.

Example

import { Component, Input, OnChanges } from '@angular/core';

@Component({

  selector: 'app-child',

  template: `

  <h3>Child Component</h3>

  <p>TICKS: {{ lifecycleTicks }}</p>

  <p>DATA: {{ data }}</p>

  `

})

export class ChildComponent implements OnChanges {

  @Input() data: string;

  lifecycleTicks: number = 0;


  ngOnChanges() {

    this.lifecycleTicks++;

  }

}


@Component({

  selector: 'app-parent',

  template: `

  <h1>ngOnChanges Example</h1>

  <app-child [data]="arbitraryData"></app-child>

  `

})

export class ParentComponent {

  arbitraryData: string = 'initial';


  constructor() {

    setTimeout(() => {

      this.arbitraryData = 'final';

    }, 5000);

  }

}

ngOnInit

ngOnInit fires once upon initialization of a component’s input-bound (@Input) properties. The next example will look similar to the last one. The hook does not fire as ChildComponent receives the input data. Rather, it fires right after the data renders to the ChildComponent template.

Example:

import { Component, Input, OnInit } from '@angular/core';


@Component({

  selector: 'app-child',

  template: `

  <h3>Child Component</h3>

  <p>TICKS: {{ lifecycleTicks }}</p>

  <p>DATA: {{ data }}</p>

  `

})

export class ChildComponent implements OnInit {

  @Input() data: string;

  lifecycleTicks: number = 0;


  ngOnInit() {

    this.lifecycleTicks++;

  }

}


@Component({

  selector: 'app-parent',

  template: `

  <h1>ngOnInit Example</h1>

  <app-child [data]="arbitraryData"></app-child>

  `

})

export class ParentComponent {

  arbitraryData: string = 'initial';


  constructor() {

    setTimeout(() => {

      this.arbitraryData = 'final';

    }, 5000);

  }

}

ngDoCheck

ngDoCheck fires with every change detection cycle. Angular runs change detection frequently. Performing any action will cause it to cycle. ngDoCheck fires with these cycles. Use it with caution. It can create performance issues when implemented incorrectly.

ngDoCheck lets developers check their data manually. They can trigger a new application date conditionally. In conjunction with ChangeDetectorRef, developers can create their own checks for change detection.

Example:

import { Component, DoCheck, ChangeDetectorRef } from '@angular/core';


@Component({

  selector: 'app-example',

  template: `

  <h1>ngDoCheck Example</h1>

  <p>DATA: {{ data[data.length - 1] }}</p>

  `

})

export class ExampleComponent implements DoCheck {

  lifecycleTicks: number = 0;

  oldTheData: string;

  data: string[] = ['initial'];


  constructor(private changeDetector: ChangeDetectorRef) {

    this.changeDetector.detach(); // lets the class perform its own change detection


    setTimeout(() => {

      this.oldTheData = 'final'; // intentional error

      this.data.push('intermediate');

    }, 3000);


    setTimeout(() => {

      this.data.push('final');

      this.changeDetector.markForCheck();

    }, 6000);

  }


  ngDoCheck() {

    console.log(++this.lifecycleTicks);


    if (this.data[this.data.length - 1] !== this.oldTheData) {

      this.changeDetector.detectChanges();

    }

  }

}

ngAfterContentInit

ngAfterContentInit fires after the component’s content DOM initializes (loads for the first time). Waiting on @ContentChild(ren) queries is the hook’s primary use-case.

@ContentChild(ren) queries yield element references for the content DOM. As such, they are not available until after the content DOM loads. Hence why ngAfterContentInit and its counterpart ngAfterContentChecked are used.


import { Component, ContentChild, AfterContentInit, ElementRef, Renderer2 } from '@angular/core';


@Component({

  selector: 'app-c',

  template: `

  <p>I am C.</p>

  <p>Hello World!</p>

  `

})

export class CComponent { }


@Component({

  selector: 'app-b',

  template: `

  <p>I am B.</p>

  <ng-content></ng-content>

  `

})

export class BComponent implements AfterContentInit {

  @ContentChild("BHeader", { read: ElementRef }) hRef: ElementRef;

  @ContentChild(CComponent, { read: ElementRef }) cRef: ElementRef;


  constructor(private renderer: Renderer2) { }


  ngAfterContentInit() {

    this.renderer.setStyle(this.hRef.nativeElement, 'background-color', 'yellow')


    this.renderer.setStyle(this.cRef.nativeElement.children.item(0), 'background-color', 'pink');

    this.renderer.setStyle(this.cRef.nativeElement.children.item(1), 'background-color', 'red');

  }

}


@Component({

  selector: 'app-a',

  template: `

  <h1>ngAfterContentInit Example</h1>

  <p>I am A.</p>

  <app-b>

    <h3 #BHeader>BComponent Content DOM</h3>

    <app-c></app-c>

  </app-b>

  `

})

export class AComponent { }

ngAfterContentChecked
ngAfterContentChecked fires after every cycle of change detection targeting the content DOM. This lets developers facilitate how the content DOM reacts to change detection. ngAfterContentChecked can fire frequently and cause performance issues if poorly implemented.
ngAfterContentChecked fires during a component’s initialization stages too. It comes right after ngAfterContentInit.

import { Component, ContentChild, AfterContentChecked, ElementRef, Renderer2 } from '@angular/core';

@Component({
  selector: 'app-c',
  template: `
  <p>I am C.</p>
  <p>Hello World!</p>
  `
})
export class CComponent { }

@Component({
  selector: 'app-b',
  template: `
  <p>I am B.</p>
  <button (click)="$event">CLICK</button>
  <ng-content></ng-content>
  `
})
export class BComponent implements AfterContentChecked {
  @ContentChild("BHeader", { read: ElementRef }) hRef: ElementRef;
  @ContentChild(CComponent, { read: ElementRef }) cRef: ElementRef;

  constructor(private renderer: Renderer2) { }

  randomRGB(): string {
    return `rgb(${Math.floor(Math.random() * 256)},
    ${Math.floor(Math.random() * 256)},
    ${Math.floor(Math.random() * 256)})`;
  }

  ngAfterContentChecked() {
    this.renderer.setStyle(this.hRef.nativeElement, 'background-color', this.randomRGB());
    this.renderer.setStyle(this.cRef.nativeElement.children.item(0), 'background-color', this.randomRGB());
    this.renderer.setStyle(this.cRef.nativeElement.children.item(1), 'background-color', this.randomRGB());
  }
}

@Component({
  selector: 'app-a',
  template: `
  <h1>ngAfterContentChecked Example</h1>
  <p>I am A.</p>
  <app-b>
    <h3 #BHeader>BComponent Content DOM</h3>
    <app-c></app-c>
  </app-b>
  `
})
export class AComponent { }

ngAfterViewInit
ngAfterViewInit fires once after the view DOM finishes initializing. The view always loads right after the content. ngAfterViewInit waits on @ViewChild(ren) queries to resolve. These elements are queried from within the same view of the component.

In the example below, BComponent’s h3 header is queried. ngAfterViewInit executes as soon as the query’s results are available.

import { Component, ViewChild, AfterViewInit, ElementRef, Renderer2 } from '@angular/core';

@Component({
  selector: 'app-c',
  template: `
  <p>I am C.</p>
  <p>Hello World!</p>
  `
})
export class CComponent { }

@Component({
  selector: 'app-b',
  template: `
  <p #BStatement>I am B.</p>
  <ng-content></ng-content>
  `
})
export class BComponent implements AfterViewInit {
  @ViewChild("BStatement", { read: ElementRef }) pStmt: ElementRef;

  constructor(private renderer: Renderer2) { }

  ngAfterViewInit() {
    this.renderer.setStyle(this.pStmt.nativeElement, 'background-color', 'yellow');
  }
}

@Component({
  selector: 'app-a',
  template: `
  <h1>ngAfterViewInit Example</h1>
  <p>I am A.</p>
  <app-b>
    <h3>BComponent Content DOM</h3>
    <app-c></app-c>
  </app-b>
  `
})
export class AComponent { }

ngAfterViewInit
ngAfterViewInit fires once after the view DOM finishes initializing. The view always loads right after the content. ngAfterViewInit waits on @ViewChild(ren) queries to resolve. These elements are queried from within the same view of the component.

In the example below, BComponent’s h3 header is queried. ngAfterViewInit executes as soon as the query’s results are available.

import { Component, ViewChild, AfterViewInit, ElementRef, Renderer2 } from '@angular/core';

@Component({
  selector: 'app-c',
  template: `
  <p>I am C.</p>
  <p>Hello World!</p>
  `
})
export class CComponent { }

@Component({
  selector: 'app-b',
  template: `
  <p #BStatement>I am B.</p>
  <ng-content></ng-content>
  `
})
export class BComponent implements AfterViewInit {
  @ViewChild("BStatement", { read: ElementRef }) pStmt: ElementRef;

  constructor(private renderer: Renderer2) { }

  ngAfterViewInit() {
    this.renderer.setStyle(this.pStmt.nativeElement, 'background-color', 'yellow');
  }
}

@Component({
  selector: 'app-a',
  template: `
  <h1>ngAfterViewInit Example</h1>
  <p>I am A.</p>
  <app-b>
    <h3>BComponent Content DOM</h3>
    <app-c></app-c>
  </app-b>
  `
})
export class AComponent { }

ngOnDestroy
ngOnDestroy fires upon a component’s removal from the view and subsequent DOM. This hook provides a chance to clean up any loose ends before a component’s deletion.

import { Directive, Component, OnDestroy } from '@angular/core';

@Directive({
  selector: '[appDestroyListener]'
})
export class DestroyListenerDirective implements OnDestroy {
  ngOnDestroy() {
    console.log("Goodbye World!");
  }
}

@Component({
  selector: 'app-example',
  template: `
  <h1>ngOnDestroy Example</h1>
  <button (click)="toggleDestroy()">TOGGLE DESTROY</button>
  <p appDestroyListener *ngIf="destroy">I can be destroyed!</p>
  `
})
export class ExampleComponent {
  destroy: boolean = true;

  toggleDestroy() {
    this.destroy = !this.destroy;
  }
}