Checking if JSON object from promise is null - javascript

I had another similar topic open and it received negative response. I am facing a legitimate issue here and assure you I have researched this extensively. I believe my real issue is probably the syntax as I am not a proficient JS coder. This has been an ongoing struggle for an embarrassing 2 weeks now. I have the following:
fetch('https://example.com/api/submission?data.dateOfService=' + data.dateChanger + '&select=data.endingPettyTotal')
.then(response => response.json())
.then(data => instance.setValue(data[0].data.endingPettyTotal));
I am trying to look at the JSON object and if it's length is zero, set my data.engingPettyTotal to '0'. If not zero, then set it equal to the JSON object's value, like I have above.
It seems I should be able to accomplish this by checking the response.json().length, something similar to this
fetch('https://example.com/api/submission?data.dateOfService=' + data.dateChanger + '&select=data.endingPettyTotal')
.then(response => {
if(response.json().length === 0) {
console.log("empty")
return 0;
}
else {
console.log("not empty")
return
})
.then(data => instance.setValue(data[0].Balance));
}
Unfortunately this does not seem to be working either. Again, assuming I have just messed up syntax or something but then again this async stuff is confusing. Also assume this could be done with lodash (isEmpty or isNull).

response.json() returns a promise that resolves with the server sent data
Do your check in the second then()
fetch('https://example.com/api/submission?data.dateOfService=' + data.dateChanger + '&select=data.endingPettyTotal')
.then(response => {
if(!response.ok){
return Promise.resolve(0)// or just throw error
}
return response.json())
}).then(data =>
// if not array or empty array set as zero
const val = (Array.isArray(data) && data.length) ? data[0].Balance : 0;
instance.setValue(val);
})

response.json() returns a Promise object, try:
fetch('http://your.url')
.then(response => response.json())
.then(data => instance.setValue(data.length && data[0].Balance));
or if you don't want to set value if data.length equals 0:
fetch('http://your.url')
.then(response => response.json())
.then(data => data.length && instance.setValue(data[0].Balance));

it's hard to tell exactly what your parameter's names are... are they "data.dateofService" on the server Side? (assuming below that it is just 'dateOfService')
sending data via json/FormData have different handling on the PHP side.
an alternate to sending json - is new FormData()... and append('key',"value");
and instead of jsonData attach the formData to the body attribute.
const sendData = {
dateOfService: data.dateChanger,
select:data.endingPettyTotal
}
const jsonData = JSON.stringify(sendData);
const options = {
method:"POST",
body: jsonData
}
fetch('https://example.com/api/submission',options)
.then(response => response.json())
.then(data=>
{
if(data.length == 0) {
console.error("no data")
}
else {
console.log("not empty")
instance.setValue(data[0].Balance);
}
});

You're not returning the a promise that returns the JSON from your first callback function.
Put the check in the second .then().
fetch('https://example.com/api/submission?data.dateOfService=' + data.dateChanger + '&select=data.endingPettyTotal')
.then(response => response.json())
.then(data => {
if (data.length == 0) {
console.log("empty");
} else {
console.log("not empty");
instance.setValue(data[0].data.endingPettyTotal));
}
});

Related

Parse API responce with javascript

I have got the response from the JSON API, but I don't know how to parse it, it just comes back with an error, I don't know enough about it to figure it out, it returns:
(node:36308) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token o in JSON at position 1
var fetch = require('node-fetch');
fetch('https://sv443.net/jokeapi/v2/joke/Any', function(res){
if (res.ok) {
return res;
} else {
console.log(res.statusText);
}
})
.then(res => res.json())
.then((json) => {
var parsedData = JSON.parse(json)
console.log(parsedData.joke);
});
You just need to do the following to access the delivery.
fetch("https://sv443.net/jokeapi/v2/joke/Any?type=single")
.then(response => {
return response.json();
})
.then(json => {
// likely to be json.delivery but cannot
// confirm until rate limits have been lifted
console.log(JSON.stringify(json));
})
.catch(err => {
console.log(err);
});
Try this:
fetch('https://sv443.net/jokeapi/v2/joke/Any', function(res){
if (res.ok) {
return res;
} else {
console.log(res.statusText);
}
})
.then(response => response.json())
.then(data => console.log(data));
You are already parsing it with res.json(). It returns an object (in promise) which can be accessed directly. Depending on a type prop you may have different props to check for. For example twopart joke will have setup: question, and delivery: answer

retrieving json data by a key

const username = 'merMan';
fetch("./datz.json")
.then(response => response.text())
.then((response) => {
console.log(response);
})
my data response looks like below, still having a difficult time simply getting a user specific data. My response data outputs like below. I have tried using find, but always returns find is not a function, response[username] does not work either.
[{"mermAn":{"baseMapId":"459cc334740944d38580455a0a777a24","customBaseMap":"","zoomn":"5","orient":"0","centLon":"-93.69999999999843","centLat":"38.64999999999935"},
{"catWoman":{"baseMapId":"459cc334740944d38580455a0a777a24","customBaseMap":"","zoomn":"5","orient":"0","centLon":"-93.69999999999843","centLat":"38.64999999999935"},
{"Riddler":{"baseMapId":"459cc334740944d38580455a0a777a24","customBaseMap":"","zoomn":"5","orient":"0","centLon":"-93.69999999999843","centLat":"38.64999999999935"}}]
You need to parse the response after response.text(), like:
fetch("./datz.json")
.then(response => response.text())
.then((response) => {
try {
const parsedArray = JSON.parse(response);
console.log(parsedArray);
} catch (error) {
// response could not be parsed
}
})
Use .json() instead of .text()
const username = 'merMan';
fetch("./datz.json")
.then(response => response.json())
.then((users) => {
console.log(users.find(x => typeof x[username] !== "undefined"));
})

return result from observable in JS

I have a function that has an observable object and I need to return the value of the fetch that I use in this function. But I don't know why I can not return the result when I display the result it is totally fine but when I try to return it is empty.
I check a few similar problems but they were very complex and also they didn't match my case and also after trying one or two of them still the problem exists.
function getRandomQuote() {
const obs$ = Observable.create(async(observer) => {
const result = await fetch(RANDOM_QUOTE_API_URL)
.then(Response => Response.json())
.then(data => data.content)
observer.next(result)
console.log(result)
})
return obs$.subscribe(x => { return x })
}
I tried to use return only inside the subscribe part but it doesn't work and in one of the similar cases they tried to return the outer part which I tried and still not work
I am new with observable and JavaScrip I just need to return this value and use it in another function.
thank you
You should return Observable other than Subscription
function getRandomQuote() {
return Observable.create(async(observer) => {
const result = await fetch(RANDOM_QUOTE_API_URL)
.then(Response => Response.json())
.then(data => data.content)
observer.next(result)
})
}
//usage
getRandomQuote().subscribe(console.log)
Or there is defer() and from() operator which helps you convert promise to observable
getRandomQuote=()=>defer(()=>from(fetch(RANDOM_QUOTE_API_URL)
.then(Response => Response.json())
.then(data => data.content))
//usage
getRandomQuote().subscribe(console.log)

Check if json contains a key in react-native

I'm kinda new to react-native (and javascript in general). At the press of a button, I want to search a json api for a certain key (in this case a movie).
For example, heres the api https://facebook.github.io/react-native/movies.json
Now on the press of a button, I want to check if the api contains a movie named "The Matrix".
The networking tutorial states that to fetch the json, you need the following method :
function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}
This returns a json object, but how would one query this object to check if it contains a movie named "The Matrix" for example?
Any help would be greatly appreciated.
What you would do is use Array.prototype.find() for movies array in the json response and check for the value
function getMoviesFromApiAsync() {
return fetch('https://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}
//from where you are calling getMovies
getMoviesFromApiAsync()
.then(response => {
var data = response.find((movie) =>
movie.title.toUpperCase().indexOf('THE MATRIX') > -1
)
console.log(data)
if(data) {
console.log('found');
}
})
The other options are to use
Array.prototype.some()
var data = response.some((movie) => movie.title.toUpperCase().indexOf('THE MATRIX') > -1)
Array.prototype.filter()
var data = response.filter((movie) => movie.title.toUpperCase().indexOf('THE MATRIX') > -1)

Javascript - Response undefined fetch

I'm having some issues understanding variables and functions using fetch.
I'm trying to pass the value of response from
.then(response => response.json())
to
.then(lang => response['lang'].slice(-2)
But I am getting the undefined variable response error, so I'm not referencing the variable correctly. What's the correct way of calling it?
Also I want to call both console logs, the piece of code below currently does that but I don't think I should be overwriting response function, can I call a function without arguments or the commands by themselves?
.then(response => console.log(response['text']) & console.log(food))
console.log(response['text']) & console.log(food)
fetch("https://localhost:8000", {method:"POST", body:fd})
.then(response => response.json())
.then(lang => response['lang'].slice(-2))
.then(food => "Temporary")
.then(function detectType(lang) {
switch(lang) {
case 'abc':
food = "Bananas";
break;
case 'def':
food = "Apples";
break;
default:
food = "Bananas";
break;
}})
.then(response => console.log(response['text']) & console.log(food))
.catch(err => console.error(err));
}
If I'm understanding what you want to do, keep in mind that the return value of one function is the state received by the next function. So you'd be looking to do something more like this:
fetch("https://localhost:8000", {method:"POST", body:fd})
.then(response => response.json())
.then(response => {
response['lang'] = response['lang'].slice(-2);
return response;
})
.then(response => {
response['food'] = "Temporary";
return response;
})
.then(function detectType(response) {
switch(response['lang']) {
case 'abc':
response['food'] = "Bananas";
break;
case 'def':
response['food'] = "Apples";
break;
default:
response['food'] = "Bananas";
break;
}
return response;
})
.then(response => {
console.log(response['text']);
console.log(response['food']);
})
.catch(err => console.error(err));
}
Regarding fetch(), remember that it is very 'Promise heavy'.
fetch("https://localhost:8000", {method:"POST", body:fd}) returns a Promise, which you handle with the first then()
then(response => response.json()) returning response.json() will give you the state of response.json() in the next .then(). So, you have access to the JSON representation of the response by the next then().
Let's take a look at how it should look:
fetch("https://localhost:8000", {method:"POST", body:fd})
.then(response => response.json())
.then(jsonResp => jsonResp['lang'] );
By that last line, you can check the JSON object and its keys without going down a Promise chain. If you want to check the lang attribute, you have access to it the way it's seen on the example.
Hope this helps!

Categories

Resources