So basically I am trying to learn promises, The only thing that is bothering me is , I am not able to render the message of promise to the frontend page. Everything else is going fine.I also need to understand what more can we do inside resolve, is it a function ? can we do more activity there ?
import "./testAPI.css"
// import react from "react"
function testAPI() {
let test = new Promise(async (resolve, reject) => {
const res = await fetch("/testAPI").then((res) => res.json());
if(res.status === "Successful"){
resolve("API Fetch is Successful")
}
else {
reject("Could not fetch API")
}
})
test.then((message) => {
console.log(message)
return message;
}).catch((message) => {
console.log(message)
})
return (
<>
<div className="message" >This is message {message} </div>
</>
);
}
export default testAPI;
The error I am getting is
src/components/testAPI/testAPI.js
Line 24:52: 'message' is not defined no-undef
How to render the message variable's value on the page ?
You need to rewrite your component to make use of
State - to change the value over time. For example you have a message which doesn't exist unless you made an api call . To preserve the values which changes over time we use state in react . setMessage is to trigger a re-render for the component. So you made the API call and have the message but how will the react know that you need to show this message which you got from the Api call ? . so do that react useState has the second element in the array a state updater function. if you call it the component will re-render causing the UI to be sync in with the latest changes .
useEffect - to trigger the api call when the component is mounted .
import "./testAPI.css"
import { useState } from "react"
function testAPI() {
const [ message , setMessage ] = useState(null);
const makeApiCall = async () => {
try {
const response = await fetch("/testAPI").then((res) => res.json());
const result = await response.json();
if(result.status === "Successful"){
setMessage("API Fetch is Successful")
}
}catch(error){
setMessage("Could not fetch API")
}
}
useEffect(() => {
makeApiCall()
}, [])
return (
<>
{ message && (<div className="message" >This is message {message } </div>)}
</>
);
}
export default testAPI;
Related
I‘m trying to add a login response component to my application.
I‘d like to call the endpoint at the initial loading of the SPA.
The Endpoint calls a Java Class, which verifys the user (already working).
I don‘t know how to call the Endpoint initially and render a Response Modal after.
I am new to react and FetchAPI.
just don't show it until the data is loaded:
function X(){
const [data, setData] = useState()
useEffect(() => {
fetch(url).then(r => r.json()).then(setData)
}, [])
return <>
{data && <Modal data={data}/>}
</>
}
I have tried multiple approaches but nothing seems to be working
Here's what I have done,
Created a Cloud9 Instance, initiated a maven application, added aws sdk java, x-ray core, x-ray instrumentor, x-ray sdk dependencies, Created DynamoDB Client ran the application, data inserted but error subsegment not found. Manually added segment, Error gone but no traces.
Create Spring Boot App, added same dependencies, added Xray servlet filter, added begin segment, begin subsegment, no error but no traces.
I have more approaches as well but these seems to be very close. Also I have not installed any agent or Daemon. Can anyone tell where I am going wrong?
I am trying to create a simple java application, even a single page to insert data in DynamoDB and get the traces that's it.
i don't have experience working on java sharing here Node JS example hope that will be helpful. tested this : https://github.com/aws-samples/aws-xray-sdk-node-sample
const AWSXRay = require('aws-xray-sdk');
const XRayExpress = AWSXRay.express;
const express = require('express');
// Capture all AWS clients we create
const AWS = AWSXRay.captureAWS(require('aws-sdk'));
AWS.config.update({region: process.env.DEFAULT_AWS_REGION || 'us-west-2'});
// Capture all outgoing https requests
AWSXRay.captureHTTPsGlobal(require('https'));
const https = require('https');
// Capture MySQL queries
const mysql = AWSXRay.captureMySQL(require('mysql'));
const app = express();
const port = 3000;
app.use(XRayExpress.openSegment('SampleSite'));
app.get('/', (req, res) => {
const seg = AWSXRay.getSegment();
const sub = seg.addNewSubsegment('customSubsegment');
setTimeout(() => {
sub.close();
res.sendFile(`${process.cwd()}/index.html`);
}, 500);
});
app.get('/aws-sdk/', (req, res) => {
const ddb = new AWS.DynamoDB();
const ddbPromise = ddb.listTables().promise();
ddbPromise.then(function(data) {
res.send(`ListTables result:\n ${JSON.stringify(data)}`);
}).catch(function(err) {
res.send(`Encountered error while calling ListTables: ${err}`);
});
});
app.get('/http-request/', (req, res) => {
const endpoint = 'https://amazon.com/';
https.get(endpoint, (response) => {
response.on('data', () => {});
response.on('error', (err) => {
res.send(`Encountered error while making HTTPS request: ${err}`);
});
response.on('end', () => {
res.send(`Successfully reached ${endpoint}.`);
});
});
});
app.get('/mysql/', (req, res) => {
const mysqlConfig = require('./mysql-config.json');
const config = mysqlConfig.config;
const table = mysqlConfig.table;
if (!config.user || !config.database || !config.password || !config.host || !table) {
res.send('Please correctly populate mysql-config.json');
return;
}
const connection = mysql.createConnection(config);
connection.query(`SELECT * FROM ${table}`, (err, results, fields) => {
if (err) {
res.send(`Encountered error while querying ${table}: ${err}`);
return;
}
res.send(`Retrieved the following results from ${table}:\n${results}`);
});
connection.end();
});
app.use(XRayExpress.closeSegment());
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
I am new to angular and I have a requirement where I need to perform some operations to the incoming data and then show it in a table.
my current code fetches data from back end and shows it in a table.
But, what I need is to first store incoming data in a array object and then perform some operations (if else conditions and basic calculations)and then show it in the table.
export interface PeriodicElement {
"date":'',
"endDate":'',
"groupa":'',
"hoA":'',
"hoB":'',
"hoC":'',
"mCommission":''
}
const ELEMENT_DATA: PeriodicElement[] = [];
#Component({
selector: 'kt-dynamic-table',
templateUrl: './dynamic-table.component.html',
styleUrls: ['dynamic-table.component.scss'],
})
export class DynamicTableComponent implements OnInit , PipeTransform {
tableData : any;
displayedColumns: string[] = ['date', 'endDate', 'groupa',
'hoA','hoB','mCommission','action'];
dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
myTable:any;
inputData:any;
loggedData : any;
index : number;
updateStatus : boolean = false;
#ViewChild(MatSort, { static: true }) sort: MatSort;
constructor( private apiService:ApiService ,private cdRef: ChangeDetectorRef) {
}
ngOnInit(): void {
console.log('Dynamic Table');
this.inputData = {
"date":'',
"endDate":'',
"groupa":'',
"hoA":'',
"hoB":'',
"hoC":'',
"mCommission":'',
};
this.myTable = [];
this.loggedData = JSON.parse(localStorage.getItem("loggedData"));
console.log(this.loggedData.id);
this.getTableData();
this.cdRef.detectChanges();
}
getTableData(){
let url = 'http://test1-env.jkbp6sft6f.ap-south-1.elasticbeanstalk.com/api/maMaster';
this.apiService.GET(url).subscribe((resp: any) => {
this.tableData = resp.body;
this.updateTable(this.tableData);
console.log(this.tableData);
this.cdRef.detectChanges();
}, err => {
console.log(err);
});
}
What I am expecting is to get data from back end in array object.
like:
PeriodicElement[] = incoming data
then perform operations then show it in a datatable.
Your interface properties should have proper typing instead of ''
export interface PeriodicElement {
date:string,
endDate:string,
groupa:string,
hoA:string,
hoB:string,
hoC:string,
mCommission:string
}
then change your get call to
this.apiService.GET(url).subscribe((resp: any) => {
let data:PeriodicElement[] =resp.body;
//here perform some opration with data eg. data.map etc.
this.tableData = data;
this.updateTable(data);
this.cdRef.detectChanges();
}, err => {
console.log(err);
});
You could do something like this:
export interface PeriodicElement {
date:string,
endDate:string,
groupa:string,
hoA:string,
hoB:string,
hoC:string,
mCommission:string
}
And then, in your get you can specify your specific type:
this.http.get<PeriodicElement >(url).subscribe(response =>{
let data:PeriodicElement[] = response ;
});
This way you can directly map response without using pipe filters or map operators.
Bingo!!,
You can use .map function provided by RxJs
this.http.get<PeriodicElement >(url).subscribe(response =>{
let data:PeriodicElement[] = response ;
});
just write this code like:
.map(response =>{
// your working logic should go here now. This the standared way to deal with the
responses
}).subscribe(response =>{
let data:PeriodicElement[] = response ;
});
I'm trying to call a function that returns me a json object from a servlet through a link.
My HTML link, call fTest function:
<td>ver</td>
My controller:
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga){
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {$scope.descargas = response.descargas;});
$window.alert(JSON.stringify($scope.descargas));
};
});
when I press for the first time the link appears "undefined" in the alert
but when I press a second time if I can see the json object that returns in the alert
What may be happening when I press first the link? please help
thanks
The problem here is your are alerting $scope.descargas outside of the success callback therefore it truly is not defined yet try modifying it like this.
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga){
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {
$scope.descargas = response.descargas;
$window.alert(JSON.stringify($scope.descargas));
});
};
});
Since every server side request using $http in Angular is an AJAX i.e. an asynchronous call to server, you are assuming that your alert method will be called after the success response execution complete. But this is wrong.
This is where the concept of promises comes in Angular.
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga) {
console.log("1");
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {
$scope.descargas = response.descargas;
console.log("2");
});
console.log("3");
$window.alert(JSON.stringify($scope.descargas));
};
});
So when you execute this code with a delay at server side, you will see the order of console log as: 1, 3 and 2.
So, your success function is executed when the response received from the server. So for the first time, the value in descargas variable is null but get's stored using first server response and next time, value from previous call is being displayed.
I am using Dojo and making an AJAX call to a JAVA Class and trying to get the output of the program to an Alert box to the client.
var showResult = function(result){
console.log("Showing Result()");
var store = new dojo.data.ItemFileReadStore({ data: result});
console.dir(store);
store.fetch( { onItem: function(data) { alert("Hie"); },
onError: function(error,request){ alert("ERROR");}
});
};
This is my code, showResult basically is call back function from xhr request. I can see console.dir(store) printed onto Firebug but the fetch function always returns the onError block.
My store array is of the form {info="Test Message"} and I need to retrieve "Test Message" and display it in an Alert box. Any help?
If the result is just an array, you should use new dojo.data.ItemFileReadStore({data : {items : result}}) to create the store.
For example, result is [{info : "Test Message 1"}, {info : "Test Message 2"}], then the code should be:
var store = new dojo.data.ItemFileReadStore({data : {items : result}});
store.fetch({
onItem : function(item) {
alert(store.getValue(item, "info"));
},
onError : function(error) {
alert("Error!");
}
});
Try
store.fetch({query: {info: '*'}},
onItem: function(data) {
alert("Hie");
},
onError: function(error, request) {
alert("ERROR");
}
);
as well you may want to see if onComplete: function(items){console.log(items);} works instead of onItem, it is worth a try.
As well console.log your error so that you can see what the issue is.
A few other things do you store have an identifier and label set?