Sunday, 20 February 2022

React - Multiple HTTP API call using Axios.all &&& Promise.all - fill in ag-grid-react

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

import Axios from "axios";
import { 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 "./styles.css";
//import 'prop-types' from 'props-types';

export default function App() {
//-------------------------------------------------------------------------
//Type-1 static column data to render ag-React grid table
const [staticColumnDefs] = useState([
{ field: "make" },
{ field: "model" },
{ field: "price" }
]);
const [staticRowData] = useState([
{ make: "Toyota", model: "Celica", price: 35000 },
{ make: "Ford", model: "Mondeo", price: 32000 },
{ make: "Porsche", model: "Boxter", price: 72000 }
]);
//-------------------------------------------------------------------------
const userApi = "https://jsonplaceholder.typicode.com/users";
const postApi = "https://jsonplaceholder.typicode.com/posts";
//-------------------------------------------------------------------------
const axiosColumnDefss = [
{ headerName: "User Name", field: "post.username" },
{ headerName: "Title", field: "title" },
{ headerName: "Post", field: "body" }
];

const [axiosRowsData, setAxiosRowsData] = useState([]);
const [users, setUsers] = useState();
const [posts, setPosts] = useState();

const getUserPost = () => {
Axios.all([Axios.get(userApi), Axios.get(postApi)])
.then(
Axios.spread((...responses) => {
setUsers(responses[0].data);
setPosts(responses[1].data);
//console.log(users, posts);
// To use const or let varabile to do operations

responses[1].data.map(function (item1) {
responses[0].data.map(function (item2) {
if (item1.userId === item2.id) {
item1.post = item2;
}
});
});
//mystery here is post, user are not reassigning with consoel gives
//console.log("Result=>" + responses[1].data, users, posts);
setAxiosRowsData(responses[1].data);
})
)
.catch((errors) => {
// react on errors.
console.log(errors);
});
};
//---------------------------------------------------------------------------
const [promiseRowsData, setPromiseRowsData] = useState([]);
const promiseColumnDefss = [
{ headerName: "User Name", field: "post.username" },
{ headerName: "Title", field: "title" },
{ headerName: "Post", field: "body" }
];

const PromiseAll = async () => {
try {
const res = await Promise.all([Axios.get(userApi), Axios.get(postApi)]);
const data = res.map((res) => res.data);
//console.log(data[0], data[1], data, data.flat());
data[1].map(function (item1) {
data[0].map(function (item2) {
if (item1.userId === item2.id) {
item1.post = item2;
}
});
});

//console.log("Result=>" + data[1]);
setPromiseRowsData(data[1]);
} catch {
throw Error("Promise failed");
}
};

useEffect(() => {
getUserPost();
PromiseAll();
}, []);

return (
<>
<h5> Static Table Data</h5>
<div className="App ag-theme-alpine" style={{ height: 200, width: 600 }}>
username | post | title
<AgGridReact columnDefs={staticColumnDefs} rowData={staticRowData} />;
</div>
<br />
<h5> Axios.all ( multi http call) Table Data</h5>
<div className="App ag-theme-alpine" style={{ height: 400, width: 600 }}>
username | post | title
<AgGridReact columnDefs={axiosColumnDefss} rowData={axiosRowsData} />;
</div>
<br />
<h5> Promise.all ( multi http call) asyn await.then() -Table Data</h5>
<div className="App ag-theme-alpine" style={{ height: 400, width: 600 }}>
username | post | title
<AgGridReact
columnDefs={promiseColumnDefss}
rowData={promiseRowsData}
/>
;
</div>
</>
);
}

Wednesday, 16 February 2022

Convert Array of Object to array AND array to Array of Object - using map function in JS/TS

Convert  JSON ARRAY to Array

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

var someJsonArray  = [

                                   {id:1, name: 'name1', property:'value1'},

                                    {id:2, name: 'name2', property:'value2'},

                                    id:3, name: 'name3', property:'value3},

                                    ];


using Arrow function:

-------------------------

var arrayData = someJsonArray.map( item => item.property )     

/// output is ::: ['value1', value2','value3'];


///using without  Arrow (=>) function

-----------------------------------------------

var arrayData someJsonArray.map( function(item) { return item.property; } );  


Convert  ARRAY to JSON Array

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


var arr =  ['value1', value2','value3'];

let JsonArr = arr.map( val => { "key": val,"name": val, "value": val } 

 // this case all the key values same data   [{key:1, name: 'name1', val:'value1'}, {}, {}]

without Arrow Function( => )

let JsonArr = arr.map( function(val)=> { return {"name": val, "value": val }  }); 




Wednesday, 9 February 2022

How to deploy a React App to github Pages with github Actions:

 How to deploy a React App to github Pages with github Actions:

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


 create a repo in github.

 

 Clone the peoject and then create react application

 

npx create-react-app react-github-pages-actions


npm install


npm i gh-pages --save-dev


add the package.json


 { 

 "name": "react-github-pages-actions",

 THEN "homepage": "https://[GITHUB_USERNAME}.github.io/react-github-pages-actions   {project name}

 ...

 ...

 }

 ,

 "scripts": {

"predeploy": "npm run build",

"deploy" : "gh-pages -d build",    // gh-pages is ceate a new branch to deploy from                                                                                 the branch  merge the feature branch into main branch 

 // from main to gh-page will carete clone

"start": "react-script start",  

....

....

...

}

Once the development is completed, run predeploy cmd


THEN run the deploymnet command



goto github -> settings -> pages -> you can see the url is deploy in github pages.

We can change the branch name and post the root/ docs save

Addding Github actions to react project:

---------------------------------------

create .github folder in the project root directory inside create another directory -> workflow (folder ) -> then create file workflow.yml


Monday, 31 January 2022

How to check data type or validate data in React js

 there are two data types in Javascript 

primitive 


String, 

Number, 

Boolean, 

Undefined, 

and NULL 


non-primitive types:

Object,

 Array,

 and RegExp

 To check the data belongs to which data type there is an inbuilt javascript method called typeof. typeof can be used for validating the data type but there is one weird behavior of typeof Array that it gives us object as output.

console.log(typeof(new Date())) // object

console.log(typeof(['Manish', 'Manntrix', "Medium"])) // object

console.log(typeof({ name: 'Manish', age: 26 })) // object

console.log(typeof(/ab+c/i)) // object

console.log(typeof(new Error('Error')))  // object


To solve the issue 

  1. Open your project directory and install xtypejs.
npm install xtypejs --save

2. Now import xtype from xtypejs library.

import xtype from 'xtypejs'
console.log(xtype(new Date())) // date console.log(xtype({})) // empty_object
console.log(xtype({name: "manish"})) // single_prop_object
console.log(xtype({name: "manish", age: 26})) // multi_prop_object
console.log(xtype([])) // empty_array
console.log(xtype([1])) // single_elem_array
console.log(xtype([1, 2])) // multi_elem_array
console.log(xtype(undefined)) //undefined
console.log(xtype(1)) //positive_integer
console.log(xtype(1.1)) //positive_float
console.log(xtype(-1.1)) //negative_float
console.log(xtype(-1)) //negative_integer
console.log(xtype('Hello')) //multi_char_string
console.log(xtype(' ')) //whitespace
console.log(xtype('')) //empty_string
console.log(xtype(NaN)) //nan
console.log(xtype(new Error())) //error
console.log(xtype(/ab+c/i)) //regexp
console.log(xtype(true)) //true
console.log(xtype(false)) //false

//Example 2 (Validate with correct data type) ============================================== console.log(xtype.type(new Date())) // date
console.log(xtype.type({})) // object
console.log(xtype.type({name: "manish"})) // object
console.log(xtype.type({name: "manish", age: 26})) // object
console.log(xtype.type([])) // array
console.log(xtype.type([1])) // array
console.log(xtype.type([1, 2])) // array
console.log(xtype.type(undefined)) //undefined
console.log(xtype.type(1)) //number
console.log(xtype.type(1.1)) //number
console.log(xtype.type(-1.1)) //number
console.log(xtype.type(-1)) //number
console.log(xtype.type('Hello')) //string
console.log(xtype.type(' ')) //string
console.log(xtype.type('')) //string
console.log(xtype.type(NaN)) //nan
console.log(xtype.type(new Error())) //error
console.log(xtype.type(/ab+c/i)) //regexp
console.log(xtype.type(true)) //boolean
console.log(xtype.type(false)) //boolean
Full e-g
Class component ;eve; constructor(props){
super
(props)
this.state = {
data: []
}
} Hooks level - function component const[ApiData, setApiData ] useState([]); useEffect({ getData(); },[])
async getData (){
const res = await axios.get('https://jsonplaceholder.typicode.com/users')
if(xtype.type(res.data) === 'array'){
this.setState({data: res.data})
}else{
console.log(new Error('Something went wrong'))
this.setState({data: []})
}
}
componentDidMount(){
this.getData()
}
render() {
return (
<div>
{this.state.data.map(d => <h5>{d.name}</h5>)}
</div>
)
} Ref: https://medium.com/how-to-react/how-to-check-data-type-or-validate-data-in-react-js-a172eceed8a8#:~:text=String%2C%20Number%2C%20Boolean%2C%20Undefined,inbuilt%20javascript%20method%20called%20typeof.

KISS, DRY, SOLID, YAGNI — A Simple Guide to Some Principles of Software Engineering and Clean Code

1 — KISS (Keep It Simple, Stupid)  Simplicity triumphs over complexity. Direct and clear codes are better for developing, maintaining, and s...