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