How to reuse fetched data from API? - javascript

I'm fetching data from a API that returns a JSON object:
fetch("api.php")
.then(function(response) {
console.log("Status: " + response.status);
if (response.ok) {
return response.json();
} else {
throw Error(response.status);
}
}).then(function(json) {
json.forEach(function(item) {
// 'datas' contains the items extracted from the JSON response
datas.add(item);
});
}).catch(function(err) {
console.log(error);
});
If I want to query the data with jinqJs I can change the code slightly to:
}).then(function(json) {
var result = new jinqJs()
.from(json)
.where('start_date = 2017-03-10')
.select();
result.forEach(function(item) {
datas.add(item);
});
}).catch(function(err) {
and it works really well.
My question is: due to the fact that by fetching only once the API I actually download ALL the needed data how can I query it 'outside' the forEach fetch?. I mean: I already have all the data with one call to the API, I can easily do queries on the data with jinqJs why should I call the API every time I need to query it? Is it possible to query datas once the forEach has added all the items?
For example, outside the forEach (notice the .from(datas) instead of .from(json)) I could do:
var result = new jinqJs()
.from(datas)
.where('start_date = 2017-03-10')
.select();
and get the same result.
As I'm trying to build a mobile app, this would be handy because I would bind the above code to specific buttons and query the data accordingly and I would connect to the internet only the first time the app is started rather than every time a query is needed.

Assign the "JSON" promise to a variable
var something = fetch("api.php")
.then(function(response) {
console.log("Status: " + response.status);
if (response.ok) {
return response.json();
} else {
throw Error(response.status);
}
});
Now you can use something as many times as you like
something
.then(json => console.log(json))
.catch ...
something.then(json => new jinqJs()
.from(json)
.where('start_date = 2017-03-10')
.select()
.forEach(function(item) {
datas.add(item);
});
).catch ....

Related

Using Lambda with NodeJS and fetching value correctly from Dynamo db, I cannot process the json data recieved

//Function to pull data from Dynamo DB (works)
async function pullone(sessionid) {
const params = {
TableName: dynamodbTableName,
Key: {
'sessionid': sessionid
}
};
return await dynamodb.get(params).promise().then((response) => {
return response.Item
}, (error) => {
console.error('Do your custom error handling here. I am just gonna log it: ', error);
});
}
//executing it
`exports.handler = async (event) => {
let sessionid = "45883754"
let data = pullone(sessionid)
return data
};`
//The above works well and the 'data' returned is
{ "school": "3wc", "sessionid": "45883754" }
I have tried to get values with data.school but itdoes not work. Is this an issue with Lambda because this is supposed to be a nobrainer. Your support will be appreciated. Thanks guys
I tried data.school or data.sessionid but the values were not coming forth
For future posts, please show the error message or what you recieved that was unexpected.
Im your case, the Lambda function is doing an asynchronous call to fetch the data meaning that the lambda itself is asynchronous. In your code that calls the Lambda, you meed to add await such that the call looks like this:
let data = await pullone(sessionid)
console.log(data.school)

how to use fetch in order to get and display information

i managed to use fetch to get some information about the world population. i got the information and displayed them on my page. the is the url of getting the population of Norway (https://d6wn6bmjj722w.population.io/1.0/population/Norway/today-and-tomorrow/) and this is the list of all countries (https://d6wn6bmjj722w.population.io/1.0/countries). i'd like to know how can i send a different request (choose another country). in my code code, there's a textbox that gets a country name from the user. i want the same name to be used as request.
here's my code for fetching the information.
function fetchcountryList(){
fetch("https://d6wn6bmjj722w.population.io/1.0/countries").then(response=>{
if(!response.ok){
throw Error("ERROR")
}
return response.json();
}).then(data=>{
console.log(data.countries);
const cl=data.countries.map(user2=>{
return `<p>Country List:${user2}})</p>`
}).join()
document.querySelector("#myFetch2").innerHTML=cl;
})
.catch(error=>{
console.log(error)
})
}
function fetchCountry(){
fetch("https://d6wn6bmjj722w.population.io/1.0/population/Norway/today-and-tomorrow/")
.then(Response=> {
if(!Response.ok){
throw Error('ERROR')
}
return Response.json();
}).then(data=>{
console.log(data.total_population);
const html=data.total_population.map(user=>{
return `<p>Population: ${user.population}</p>`
}).join()
document.querySelector("#myFetch").innerHTML=html;
})
.catch(error =>{
})
}
well i don't think your second function is working, if yes then replace console.log to document.write, as you need to work with object.
in your main function where you are appending list items, pass a variable x,
like this:
const x = data.total_population.x;
list.appentchild(document.createTextNode(x));

Differentiate between redirect/JSON-data in response from fetch API request

i am trying to build a logic at front end to differentiate between the redirect and JSON response, the end goal for this is as, if the response is redirect go to that page and if the response is having data then it will render that data on the page.
Note: it is working fine if the back end send response as either res.redirect or res.json, but i am struggling (as in below code) as when i have to check first as what the response is from back end , i thought as if i can use if else statement at front end to disgusting between res.json and res.respond, i have tried like .then(res.redirect=>{…}).then(res.json=>{}) but it doesn’t look like if i am using the correct logic.
Any suggestions please, thanks :slightly_smiling_face:
Snippet from my front end code is .
const request = new Request("http://localhost:5000/api/newuser", options);
(async () => {
const incomingdata = await fetch(request)
*// below i differetiated the incoming response as if it is res.redirect or res.json data but didnt work*
.then((res.redirect) => {
window.location.href = res.url;
})
.then((res.json) => {
console.log("cannot find data");
})
.catch((err) => console.log("err"));
Snippet from my bank end code is,
connection.query("SELECT * FROM users WHERE email=?;", [x1.Email], function (
err,
results
) {
console.log("74",results, err);
console.log("75",results[0].email);
if (err) throw err;
else {
if (results[0].email && results[0].password) {
console.log("79",results[0].email);
//console.log(results[0]);
if (results[0].password == x1.password)
res.redirect("http://localhost:3000/");
else {
res.json({
data: "invalid password",
});
}
} else res.redirect("http://localhost:3000/about");
}
});
});
For redirect you can check if the HTTP code is in the 300 range, which is provided in res.status. It won't take dot notation, So, you can use
.then(res => {
if(res.status >= 300 && res.status < 400){
// redirect
} else {
return res.json();
}
})
.then(data => {
//handle your json data
});
It would be a syntax error to use a dot in the callback argument like:
.then((res.json) => {
However, it would be possible to deconstruct an object like this:
.then(({ status, json }) => {

Sort API Response without Storing the Data using JavaScript

I am using below code to call a GET API and then sort the Response with one of the object listed inside. I was told to convert the response to a ARRAY first then apply the sort function but it seems difficult and im missing some thing to sort the generated Array. Please help me, been trying for many days.
My Code:
url2 = "https://SampleAPI";
function fetchdata(){
fetch(url2)
.then(response=>{
return response.json();
})
.then(data=> {
console.log(data.data) // Getting the "Unsroted Response" Here
})
};
fetchdata(); //
const sortedResponse = ListModels.sort(function(a, b) { return parseInt(a.associateId) - parseInt(b.associateId) });
console.log("SORTED: ", sortedResponse) // Using to SORT THE RESPONSE WITH "associateId"
API Response for Above JS Code:
{
ListModels:(4) [
{
searchRank:0,
firstName:"Micheal",
lastName:"Brook",
associateId:"40",
payRateType:"Cost-only",
doctorStatus:null,
contractStartDate:"0001-01-01T00:00:00"
},
{
searchRank:0,
firstName:"Travis",
lastName:"Mayn",
associateId:"20",
payRateType:"Samp-only",
doctorStatus:null,
contractStartDate:"0001-01-01T00:00:00"
},
{
searchRank:0,
firstName:"Berry",
lastName:"Brooks",
associateId:"43",
payRateType:"Samp-only",
doctorStatus:null,
contractStartDate:"0001-01-01T00:00:00"
},
{
searchRank:0,
firstName:"Kim",
lastName:"Reed",
associateId:"25",
payRateType:"Samp-only",
doctorStatus:null,
contractStartDate:"0001-01-01T00:00:00"
}
],
totalRecord:4
}
I want to SORT above API response with "associateId" but with my Sorting line, im getting Error.
Please help me, i was told to hit the API Endpoint and sort without storing the response in CODE.
Error:
> error: Uncaught ReferenceError: ListModels is not defined
You have to move the sorting inside the response handler:
url2 = "https://SampleAPI";
function fetchdata(){
fetch(url2)
.then(response=>{
return response.json();
})
.then(data=> {
console.log(data.data) // Getting the "Unsroted Response" Here
const list = data.data;
const sortedResponse = list.sort(function(a, b) { return parseInt(a.associateId) - parseInt(b.associateId) });
console.log("SORTED: ", sortedResponse) // Using to SORT THE RESPONSE WITH "associateId" })
};
fetchdata(); //
The operations just after fetchdata are executed before the response comes from the server.

How to retrieve data from api res.send?

I am using the javascript MEAN stack for my single page app.
I have an Angular factory making a call to my Api.
app.factory('authorizing', function($resource){
return $resource(
'/api/authorizing/:username',
{'username':'#username'},
// retreiving only one user and all their roles
{'singleUser' : {
method:'GET'
,isArray: false
}}
);
});
I call the factory in my controller like this. My goal is to update the web page data based on the response I get back from the Api. I expect a true or false value to be returned. I have tried other things but I want to keep my authorization on the server side.
app.controller('usrPageController', function ($scope, usrServiceById, $route, authorizing, $rootScope) {
$scope.updateUser = function (data,field){
var vCheckUserRoles;
vCheckUserRoles = authorizing.singleUser({'username': $rootScope.current_user});
if (vCheckUserRoles == true){
usrServiceById.update({'username':username},{field:data, 'fieldName':field});
};
};
});
The database returns the result data using a res.send.
.get(function (req, res) {
RoleUser.find({ 'aclUserName': req.params.username }, function (err, aclUser) {
if (err) { return res.sendStatus(500) };
// return an error if no user is found
if (aclUser == null) { return res.sendStatus(401) };
//check for proper role in list of users
for (var i = 0; i < aclUser.length; i++) {
if (aclUser[i].aclUserResource == req.params.username + '_PROFILE') {
//return a successful status
return res.send('true');
};
};
//return a failed status
return res.send('false');
});
});
I don't get any errors from the code but the return object is empty when it hits the controller after the res.send. I have tried different types of data to return but nothing seems to work for me. Any help is appreciated. I have othe res.send calls in my Api. They work but I take the data directly from my database wiht the callback and feed it to the res.send. This is the only time in my code that I am trying to return something besides the successful callback variable.
UPDATED CODE:
I removed the var vCheckUserRoles. Now the value is passed to a success callback
app.controller('usrPageController', function ($scope, usrServiceById, $route, authorizing, $rootScope) {
authorizing.singleUser({'username': $rootScope.current_user},function(response){
console.log('response = ' + response.data)
if (response.data == 'true'){
usrServiceById.update({'username':usrSingle.username},{field:data, 'fieldName':field});
};
});
});
You can use res.json instead of res.send to send status of your query.
Example ////
res.json({status:true})
And on client side you can access that status value in data.status field.
On the server you send data as follows:
res.status(200).send({message: "Hello!"});
In the front-end you receive the data, then resolve it to get data as follows:
fetch(url)
.then(response => {
if(response.ok) {
return response.json();
}
}).then(data => {
if(data) {
console.log(data);
}
}).catch(err => console.error(err));

Categories

Resources