Wednesday 9 August 2023

React- Ag Grid Server side Pagination Implmentation

 import React, { useEffect, useState } from 'react';


import { AgGridColumn, AgGridReact } from 'ag-grid-react';


import 'ag-grid-community/dist/styles/ag-grid.css';

import 'ag-grid-community/dist/styles/ag-theme-alpine.css';


import './App.css';


function App() {

  const [gridApi, setGridApi] = useState(null);

  const perPage = 3;


  const onGridReady = (params) => {

    setGridApi(params.api);

  };


  useEffect(() => {

    if (gridApi) {

      const dataSource = {

        getRows: (params) => {

          // Use startRow and endRow for sending pagination to Backend

          // params.startRow : Start Page

          // params.endRow : End Page


          const page = params.endRow / perPage;

          fetch(`https://reqres.in/api/users?per_page=${perPage}&page=${page}`)

            .then(resp => resp.json())

            .then(res => {

              params.successCallback(res.data, res.total);

            }).catch(err => {

              params.successCallback([], 0);

            });

        }

      }


      gridApi.setDatasource(dataSource);

    }

  }, [gridApi]);


  const avatarFormatter = ({ value }) => {

    return <img src={value} width="50px" height="50px" />

  }


  return (

    <div className="App">

      <h2>Server side pagination in the React AG Grid - <a href="https://www.cluemediator.com" target="_blank">Clue Mediator</a></h2>

      <div className="ag-theme-alpine ag-style">

        <AgGridReact

          pagination={true}

          rowModelType={'infinite'}

          paginationPageSize={perPage}

          cacheBlockSize={perPage}

          onGridReady={onGridReady}

          rowHeight={60}

          defaultColDef={{ flex: 1 }}

        >

          <AgGridColumn field="first_name" headerName="First Name" cellClass="vertical-middle" />

          <AgGridColumn field="last_name" headerName="Last Name" cellClass="vertical-middle" />

          <AgGridColumn field="email" headerName="Email" cellClass="vertical-middle" />

          <AgGridColumn field="avatar" headerName="Avatar" cellRendererFramework={avatarFormatter} cellClass="vertical-middle" />

        </AgGridReact>

      </div>

    </div>

  );

}


export default App;


Thursday 6 April 2023

React- nested API call asyn - await

useEffect(() => {

  const getData = async () => {

      try {

          const { data } = await fetchContext.authAxios.get('/myapi/' + auth.authState.id);

          const customerIdList = data.map(value => value.customerID);

          // this fetches list of all customer details in one go

          const customersDetails = (await fetchContext.authAxios.post('/mySecondApi/', {customerIdList})).data;

          // please make necessary changes to the api call

          const updatedData = data.map(value => {

                 // filtering the particular customer's detail and updating the data from first api call

                 const customerDetails = customersDetails.filter(c => c.customerID === value.customerID)[0];

                  

                  return {

                      ...value, // de-structuring

                      customerID: customerDetails

                      // as you asked customer data should replace the customerID field

                  }

              }

          );

          setData(updatedData); // this data would contain the other details of customer in it's customerID field, along with all other fields returned by your first api call

      } catch (err) {

          console.log(err);

      }

  };

  getData();

}, [fetchContext]); 

CSS - regex

 


css regx proeprty You could use the ^= ('starts with') and $= ('ends with')

attribute selectors. 

[class^="dh-"]{} ---> start with dh

[class$="-bl"]{} ---> end with dl


Wednesday 5 April 2023

Angular 13 - Micro front end architecture with angular element, custom element, web compoentsjs

 Angular Micro front end with angular element, custom element, web compoentsjs

=======================================================================

MicroApp: 

Step:1 ng new MicroApp angular 13.0.0

 

ng add @angular/elements

document-register-element 

npm i @webcomponents/custom-elements --save

@webcomponents/webcomponentsjs 

ng add ngx-build-plus polyfill.js 


import'document-register-element' 

import"@webcomponents/custom-elements/src/native-shim";

import "@webcomponents/custom-elements/custom-elements.min"; 


app.module.ts


complete the All the

development of Child/Micro app as entire app or particular component as ???

Particular module??? Note: For Module will be part of any component. So, The

idea will module will become component as mciroApp 

Step:2 MicroApp:> ng add @angular/elements will generate / Impact package.json -> 

"@angular/elements" 

"document-register-element": "1.8.1", --> manull add at devDependency

then do npm install polyfill.ts ->Automatically Import this packages into

polyfills.ts file: if not do it maually import 'document-register-element';


Step:3 Install some polyfills:

 MicroApp:> npm i @webcomponents/custom-elements--save add at pakcage.json 

 "@webcomponents/webcomponentsjs ": "^2.6.0", then npm install Import those packages into polyfills.ts file: import

"@webcomponents/custom-elements/src/native-shim"; 

import "@webcomponents/custom-elements/custom-elements.min"; 

Step:4 MicroApp:> ng add ngx-build-plus will generate / Impact package.json -> "ngx-build-plus":

"^9.0.6", "architect": { "build": { "builder": "ngx-build-plus:browser ....


$while building$ "builder": 

"ngx-build-plus:build", .... 

"budget": [ // to avoid

budget Error Delete this part in Micro UI angular.json , ->budget error occurs 

{

"type": "anyComponentStyle", 

"maximumWarning": "10mb", //from 6kb

"maximumError": "10mb" // from10kb } ] 

"serve": { "builder":"@angular-devkit/build-angular:dev-server", ... 

"test": { "builder":"@angular-devkit/build-angular:karma", 

Step:5 MicroApp:> 

app.module.ts import {BrowserModule } from '@angular/platform-browser';

 import { NgModule,Injector,CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';

 import {createCustomElement } from '@angular/elements';

 bootstrap: [], //webcompionentjs will handle it. while develop it will get filled with appComponent , but in build time it must be empty schemas:

[CUSTOM_ELEMENTS_SCHEMA] // entire app as microUI 


export class AppModule { const

elm = createCustomElement(AppComponent, {injector: this.injector});

console.log('cream-index-ui custom element:::',

customElements.get('cream-index-ui')); 

if (!customElements.get('micro-app1')) {

customElements.define('micro-app1', elm); } 

}


 Step:6 build the child app and

generate dist for master/parent app MicroApp:>ng build --configuration production --output-hashing none --single-bundle true --bundle-styles false --keep-styles false 


Notes: --output-hashing none ->will avoid hashing the file

names. --single-bundle true ->will bundle all the compiled files into a single

JS file. --bundle-styles false ->if we follow the same library css for all theprojects 


Step:6.1 Sometimes budget error will occur. so, Make the correction at

MicroApp angular.json "budgets": [ { "type": "initial", "maximumWarning": "2mb",

"maximumError": "5mb" }, { "type": "anyComponentStyle", "maximumWarning": "2mb",

//from 6kb "maximumError": "5mb" // from10kb } ] copy the dist folder into

master app src/app/assets/MicroApp --> which contains Main.js, index.html,3

other files 


Step:6.2 To do the auto copy -> npm install copyfiles -g // in the

machine/ laptop MciroApp:> npm run copfiles : copyfiles ./dist/*.*

MasterAppPath/src/app/assets ALternatively : ng build make output path from MciroApp 


Step:7 To generate mutliple micro app follow the step -> Step 1- 6

Another child app or MciroApp dist Step:8 MasterApp / ContainerApp / ng new

MasterApp Step: 9 ( Repeat Step 2 ) MasterApp:> will generate / Impact

package.json -> "document-register-element": "1.8.1", --> change the version

1.8.1 if not then npm install 


Step:10 MasterApp app.module.ts import { NgModule,

CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; bootstrap: [AppComponent],

schemas: [CUSTOM_ELEMENTS_SCHEMA] // which allows custom element as recognized

element in master App }) 

export class AppModule { } 

Step:11 MastetApp: Whichever the component need to import/use the in that component MasterApp -Requried


component.component.ts 

childAppPath ='http://localhost:4200/assets/MicroApp/main.js'; 

constructor(){ } 

ngOnInit() {

this.loadScript(this.childAppPath);

 }

 loadScript(scriptPath): void { 

 var alreadyLoaded = false; for (var scriptIndex in document.scripts) { //

console.log(scriptPath, scriptIndex, document.scripts[scriptIndex].src) 

if(!alreadyLoaded && scriptPath === document.scripts[scriptIndex].src) {

alreadyLoaded = true; break; }


 } 

 if (!alreadyLoaded) { 

 const content =document.getElementById('content'); 

 const script =document.createElement('script'); 

 script.src = scriptPath;

content.appendChild(script); } 


or load style and script seperatly


loadStyles(stylePath: string): void { 

var alreadyLoaded = false; 

for (var indexin document.styleSheets) { 

if (!alreadyLoaded && stylePath ===document.styleSheets[index].href)

 { alreadyLoaded = true; break; } 

 if(!alreadyLoaded) {

 var head = document.head; 

 var style =document.createElement("link");

 style.type = "text/css"; 

 style.rel ="stylesheet"; head.appendChild(style);

 } 

 } 

 } 

 loadScript(scriptPath: string,tagName: string): void {

 var alreadyLoaded = false; 

 for (var scriptIndex in document.scripts) { 

 if (!alreadyLoaded && scriptPath === document.scripts[scriptIndex].src) {

 alreadyLoaded = true; break; 

 } 

 } if(!alreadyLoaded) { 

 const content = document.getElementById('content');

 const script = document.createElement('script'); 

 script.src = scriptPath;

content.appendChild(script); 

}


Step:12 MasterApp -


<div id="content"><micro-app1></micro-app1></div>

//

<micro-app1>

  is the custom Tag element mentioned at MicroApp app.module.ts MasterApp:> ng

  serve ==> http://localhost:4200 default if chagne the default port Change the

  ChilAppPath/port

</micro-app1>


Tuesday 21 February 2023

Angular custom npm library create and publish to npmjs artifactory

 

Create AngularLibrary from existing angular project

Assumtion : ng new Angular-App (created working with sample boiler plate code)

ng g library ngx-logger-matui

It create angular-app-> project -> ngx-logger-mat

Src src/lib ng-packagr.json package.json ... ..

to add dependent npm libraries go to angular-app->project->src->lib

npm i @material-ui, ....

then add it ng-package export ,

components, service, pipes, models we can use it.


Publish AngularLibrary

Sing up at npmjs.com

email, user, pwd are required, Email has to be verify with link

Build AngularLibrary

Angular app or workspace do angular library build

ng build ng-logger (pacakge.json at library ngs-logger-gn) to avoid naming convention

go to workspace->dist->library

cmd:>npm publish username : npmjs username &password: ****,& email public: mandate to get OTP to publish

Wednesday 15 February 2023

What are the Different Types of Errors in JavaScript? - 7 Types of error, 3 pieces of info, to handle try, catch finally

 

  • There are 7 types of JavaScript errors: Syntax errorReference ErrorType ErrorEvaluation ErrorRangeErrorURI Error and Internal Error.
  1. Syntax error - The error occurs when you use a predefined syntax incorrectly.
const func = () =>
console.log(hello)
}

Output:

}
^
SyntaxError: Unexpected token }

In the above example, an opening bracket is missing in the code, which invokes the Syntax error constructor.

  1. Reference Error - In a case where a variable reference can't be found or hasn't been declared, then a Reference error occurs.
console.log(x);

Output:

console.log(x);
            ^
ReferenceError: x is not defined
  1. Type Error - An error occurs when a value is used outside the scope of its data type.
let num = 15;
console.log(num.split("")); //converts a number to an array

Output:

console.log(num.split("")); //converts a number to an array
                ^
TypeError: num.split is not a function
  1. Evaluation Error - Current JavaScript engines and EcmaScript specifications do not throw this error. However, it is still available for backward compatibility. The error is called when the eval() backward function is used, as shown in the following code block:
try{
  throw new EvalError("'Throws an error'")
}catch(error){
  console.log(error.name, error.message)
}

Output:

EvalError 'Throws an error'
  1. RangeError - There is an error when a range of expected values is required, as shown below:
const checkRange = (num)=>{
  if (num < 30) throw new RangeError("Wrong number");
  return true
}

checkRange(20);

Output:

 if (num < 30) throw new RangeError("Wrong number");
                ^
RangeError: Wrong number
  1. URI Error - When the wrong character(s) are used in a URI function, the error is called.
console.log(decodeURI("https://www.educative.io/shoteditor"))

console.log(decodeURI("%sdfk"));

Output:

console.log(decodeURI("%sdfk"));
            ^
URIError: URI malformed
  1. Internal Error - In the JS engine, this error occurs most often when there is too much data and the stack exceeds its critical size. When there are too many recursion patterns, switch cases, etc., the JS engine gets overwhelmed.
switch(condition) {
 case 1:
 ...
 break
 case 2:
 ...
 break
 case 3:
 ...
 break
 case 4:
 ...
 break
 case 5:
 ...
 break
 case 6:
 ...
 break
 case 7:
 ...
 break
 ... up to 500 cases
 }

Output: Its output will be like InternalError.

What are Errors in JavaScript?

JavaScript code can encounter different errors when it is executed. Errors can be caused by programming mistakes, incorrect input, or other unforeseeable events.

Errors in programming can be divided into two types. These are:

  1. Program Error: - In this case, the program might need to handle this error through its error handlers. An example could be network disconnection, timeout error, etc.
  2. Developer Error: - The programmer has caused an error. It can be a syntax error, a logical error, a semantic error, etc.

The try...catch...finally Statement

Exception handling has been added to JavaScript in recent versions. Exceptions are handled by JavaScript's try...catch...finally construct and throw operator.
Syntax

try {
    // statements
    [break;]
    } 

catch ( e ) {
    // statements if an exception occurs
    [break;]
    }

finally {
    // statements that always execute regardless of an exception occurring
    }
   

Examples of errors in JavaScript

After the try block, there must either be a catch block or a finally block (or both). The catch block is executed if an exception occurs in the try block. After try/catch, finally is executed unconditionally. Let's see an example:

function myFunc() {
    var num = 50;
     try {
            alert("Value of variable a is : " + num );
        }
    catch ( error ) {
        alert("Error: " + error.description );
        }
    finally {
        alert("Finally, block will always execute!" );
        }
}
myFunc()

Output: The below statements will be shown in an alert box.

Value of variable a is : 50
Finally, block will always execute!

The throw statement can be used to raise built-in exceptions or your customized ones.

function myFunc() {
    
    var num1 = 100;
    var num2 = 0;
               
    try {
        if ( num2 == 0 ) {
            throw( "Divide by zero error." ); 
        } else {
            var num3 = num1 / num2;
        }
    }
    catch ( e ) {
        alert("Error: " + e );
    }
}
myFunc()

Output: The below statement will be shown in an alert box.

Error: Divide by zero error.

The onerror() Method

In JavaScript, error handling was simplified by the onerror event handler. If there is an exception on the page, the error event will be fired on the window object.

window.onerror = function () {
    alert("An error occurred.");
}

There are three pieces of information provided by the onerror event handler that identifies the error's exact nature.

Error message − A message similar to the one displayed by the browser when an error occurs. URL − The file where the error occurred.

Line number− This is the line number in the URL where the error occurred.

Conclusion

  • An error is a statement that interferes with the proper operation of the program.
  • There are 7 types of JavaScript errors: Syntax errorReference ErrorType ErrorEvaluation ErrorRangeErrorURI Error and Internal Error.
  • Errors in Javascript can be handled using the try...catch...finally construct as well as the throw operator.
  • The article allows you to easily identify the source of an error, whether it occurs in your terminal or browser.
REf: https://www.scaler.com/topics/types-of-errors-in-javascript/

Thursday 9 February 2023

Feb 2023 Part -2

1. Full Row edit in Ag-grid


https://blog.ag-grid.com/full-row-editing-ag-grid-committing-changes-button-click/


2

https://dev.to/antoniojuniordev/5-tips-to-improve-backend-integration-react-with-axios-b3p

3.

https://dev.to/hy_piyush/10-github-repositories-you-must-know-as-a-javascript-developer-f5d

3.2

https://github.com/mbeaudru/modern-js-cheatsheet


4. react testing 

https://www.freecodecamp.org/news/8-simple-steps-to-start-testing-react-apps-using-react-testing-library-and-jest/#:~:text=Note%20%E2%80%93%20you%20can%20also%20use,confidence%20they%20can%20give%20you.%22


5.https://github.com/rautio


6. show image before upload

https://www.kindacode.com/article/react-show-image-preview-before-uploading/


Thursday 2 February 2023

Feb 2023 Blog post,

1. React Basename router, Router, Nested Router

2. https://www.kindacode.com/cat/react/ React working models.

3. https://www.kindacode.com/cat/docker/ - Docker

4. useAxios, useFetch interceptors React 

 https://dev.to/hy_piyush/10-github-repositories-you-must-know-as-a-javascript-developer-f5d

Monday 30 January 2023

Jan 2023 Blogs list

1.React Folder structure :

 https://dev.to/fpaghar/folder-structuring-techniques-for-beginner-to-advanced-react-projects-30d7

constants folder structures


2.React Full Screen - With and without npm library

3.MFE :

module federation:

https://betterprogramming.pub/how-to-use-webpack-module-federation-in-react-70455086b2b0

https://github.com/rautio/micro-frontend-demo


single spa

https://ogzhanolguncu.com/blog/migrating-cra-to-micro-frontends-with-single-spa

4. find the text partial in search array - AutoComplete custom React

5. custom Accordion

6. custom Tabs with nav bar

7. useFetch

8. useAxios

9. React Testing library

10. jest testing for react App

11. https://www.examtopics.com/exams/amazon/aws-certified-solutions-architect-associate-saa-c02/view/2/

12. js code https://github.com/wesbos/JavaScript30