Javascript - Response undefined fetch - javascript

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!

Related

API fetch console log doesn't print properly

When using fetch method for API, does anyone know why .then(response => console.log(response.originator.name)) doesn't print any value?
console.log(response)
console.log(response.content) and console.log(response.originator.name)
I was trying to find answers for this but haven't had any luck so far. Any information would be appreciated.
function getQuote(){
fetch('https://quotes15.p.rapidapi.com/quotes/random/', options)
.then(response => response.json())
.then(response => console.log(response.content))
.then(response => console.log(response.originator.name))
.catch(err => console.error(err));}
The problem is that you put the second console.log() in a second .then(). This is receiving the result of the first console.log(), but console.log() doesn't return anything (and if it did return something, it would presumably be the object that it logged, not response). Put them both in the same .then().
function getQuote() { fetch('https://quotes15.p.rapidapi.com/quotes/random/', options)
.then(response => response.json())
.then(response => {
console.log(response.content);
console.log(response.originator.name);
})
.catch(err => console.error(err));
}

How can i use my data from a api and pass it into another function for further processing

What method is there without using setTimeout() to allow data from the fetch to be stored in the stored_data array, then allowing the test function to manipulate.
So far i get undefined.
let stored_data = []
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => stored_data.push(json))
function test(e) {
console.log(e)
}
You could simply chain another .then. You also forgot to declare store_data as a variable
let stored_data = []
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => stored_data.push(json))
.then( _ => {
// array now ready for manipulation
})

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)

Categories

Resources