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}/>}
</>
}
Related
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;
I have an AJAX call to a JAVA POJO as follows -
$.ajax({
url:'./webapi/input/approve',
type: 'PUT',
data:jsonobj,
contentType: 'application/json',
dataType:'json',
success:function(data)
{
if(!data){
alert("Invalid");
}
var values = JSON.stringify(data);
alert(values);
},
error:function(xhr,textstatus,errorthrown){
alert(xhr.responseText);
alert(textstatus);
alert(errorthrown);
}
},'json');
The corresponding Constructor in the Java Pojo that I have is as follows -
public Input(String LR, double ECH,
double CSH,String App) {
this();
lr = LR;
ech = ECH;
csh = CSH;
app = App;
}
In addition to this, I also have another Parameterised and Default Constructor in the same class. The issue that I am facing is that when I run my .jsp page, This parameterised constructor above should get called. However, When I run the same, the desired constructor does not get called. Please note that I am running Internet Explorer v 11. Also note that when I run the same on Chrome, I get the desired output.
Help much appreciated!
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'm trying to make a POST request using JavaScript routing. In the routes file:
POST /comments controllers.Clients.addComment(text: String, client: Int)
GET /assets/javascripts/routes controllers.Application.javascriptRoutes()
on page:
jsRoutes.controllers.Clients.addComment(args.text, #client.id).ajax(...);
But it creates the request
POST http://localhost:9000/comments?text=qwe&client=1 HTTP/1.1
How do I make it pass parameters in the POST body instead of a request string?
Tak a look at ajax() documentation - that is, such example:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
});
As Play JavaScript route already defines url and request method (type), you need only to add data (of course you don't need to specify them as a params in brackets)
jsRoutes.controllers.Clients.addComment().ajax(
data: {
client: #client.id,
text: args.text
}
);
Also you can send a text only to given client (determined by the URL (it can be POST but PUT looks nicer :)):
PUT /comments/:client controllers.Clients.addComment(client: Int)
in the view:
jsRoutes.controllers.Clients.addComment(#client.id).ajax(
data: { text: args.text }
);
So it will perform PUT request to http://domain.tld/comments/123 and text will be available in the form() as it was sent with POST:
public static Result addComment(int client) {
String receivedText = form().bindFromRequest().get("text");
// save it to DB ...
return ok( "Added comment: "+ receivedText+ ". for client id: " + client);
}
As i don't quite understand the JsRoutes in Play, what i did was:
In my view:
var client = 1;
$.ajax({
type: "POST",
url: "/comments/" + client,
});
And in my routes, the call to the method:
GET /comments/:client controllers.Clients.addComment(client: Int)
This works letting the browser make the request like a normal ajax call to some URL defined in routes.
I am trying to do a Spring MVC 3 ajax call to populate a drop down from json serialized data.
The problem I am seeing is I am not sure what format of JSON Spring is returning for my list, and why.
The method which returns the Ajax data looks like this:
#RequestMapping(value="/getMyObjects", method=RequestMethod.POST)
#ResponseBody
public List<MyObject> getMyObjects () {
List<MyObject> myobjects = // populate list
return myobjects;
}
And as far as I understand that should be all I need to do, right?
In my app logs I see it is indeed converting the response to JSON, as follows:
2012-06-20 11:08:21,125 DEBUG (AbstractMessageConverterMethodProcessor.java:139) - Written [[MyObject [id=1376, name=Something test], MyObject [id=1234 name=More test]]] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter#d1b7e5]
But that JSON string looks odd to me, is that valid?
I was expecting stuff like [{ id : 1376, name="Something test"}, { id : 1234, name="More test"}]
On the client side when I get the response and do an alert I see it says its an array of objects like this: [Object object] [Object object] and I dont know how to deal with this data.
I try:
alert(data); -- gives the output I just described above
$(data).each(function() {
alert(this.id); // undefined!
});
How do I use this kind of JSON data or how do I convert it to something more manageable?
[Edit] Attaching my client side code with current alert responses I am trying:
$.ajax({
type : "POST",
url : "getMyObjects",
success : function(data) {
alert(data); // [Object object] [Object object]
alert(data.value); // Undefined
$(data).each(function() {
alert(this.id); // Undefined for each iteration
});
},
error : function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
Spring 3 provides integration with DWR(direct web remoting) which is very cool framwrork for AJAX calls. In DWR you can handle lists very easily just like in core java.
This is it! you should get the json format that you were expected. no more code (parser, formatting ) in necessary.
What you dont see is the actual json returned. well you try your url right away in the browser without calling it by ajax like http://yourdomain/yourservlet/getMyObjects you then will see your json as it is.
or else, use firfox with firebug, and you can see your ajac call (request & and response)
UPDATE
$.ajax({
url: "path/to/your/url",
cache: false,
async: false,
success: function(data){
for (var i = 0; i < data.length; i++) {
alert(data[i].id);
alert(data[i].name);
}
}
});