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));
}
Related
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
})
I want to return two values from a fetch request:
stats.videoCount
stats.viewCount
Using the following code, I can return one value correctly, but cannot return both.
The following code returns the video view count.
fetch("https://api.promptapi.com/tiktok/hashtag/planttrees", requestOptions)
.then(response => response.json())
.then(treeViewCountResult => console.log(treeViewCountResult.challengeInfo.stats.viewCount))
.catch(error => console.log('error', error))
But this code won't return two values:
.then(response => response.json())
.then(treeVideoResult => console.log(treeVideoResult.challengeInfo.stats.videoCount))
.then(treeViewCountResult => console.log(treeViewCountResult.challengeInfo.stats.viewCount))
.catch(error => console.log('error', error))
treeVideoResult and treeViewCountResult will work individually, but not together.
How am I chaining the promises incorrectly?
It returns a single object. You don't need two then for it.
fetch("https://api.promptapi.com/tiktok/hashtag/planttrees", requestOptions)
.then(response => response.json())
.then(result => console.log(result.challengeInfo.stats.videoCount, resutl.challengeInfo.stats.viewCount))
I think you're misunderstanding what's happening with each then.
Everything in the example works up to this line:
.then(treeVideoResult => console.log(treeVideoResult.challengeInfo.stats.videoCount))
The result of response.json() is being given to the then function as treeVideoResult, a property of which, is being logged by console.log. However console.log returns undefined.
This means that in this line:
.then(treeViewCountResult => console.log(treeViewCountResult.challengeInfo.stats.viewCount))
treeViewCountResult is undefined. So it should throw an error (although I haven't checked).
If we want to return multiple values from one fetch call, consider using an object.
fetch("https://api.promptapi.com/tiktok/hashtag/planttrees", requestOptions)
.then((response) => response.json())
.then((treeVideoResult) => ({
videoCount: treeVideoResult.challengeInfo.stats.videoCount,
viewCount: treeVideoResult.challengeInfo.stats.viewCount,
}))
.then((result) => {
console.log(result);
doSomthingElseFunction(result);
})
.catch((error) => console.log("error", error));
TLDR: the return of one then is the input of the next. Any function using the data returned by fetch must be called inside a then (if not using async/await).
return fetch(url)
.then(response => response.json())
.then(json => {
//everything just here?
})
.catch(err => console.log(err));
Hello guys i have a newbie question. If i want to get some data from server and manage them (create new html elements, draw some canvas) am i forced to do it this way in ".then" chain? Im asking because its quite unintuitive. And ill be glad for some example of code like this, just get data from server and create/edit some html elements. Thanks!
You can do it in more intuitive way like this
getDataFromServer(url) {
return fetch(url)
.then(response => response.json());
}
async yourMainFunction() {
const data = await getDataFromServer(url);
////everything just here with data from server?
}
one thing to note that for using await you have to make your function marked with async
You are correct, the only place the response json is avalable is in the second then() callback.
You could create a function that contains your html/canvas logic and then call that function in the response callback.
fetch(url)
.then(response => response.json())
.then(json => {
handleResponse(json) // ⭐️
})
.catch(err => console.log(err));
function handleResponse (json) {
// ⭐️ everything in here
}
I'm trying to convert a response from fetch function into json format but when I do so I get an error Attempt to invoke interface method 'java.lang.string com.facebook.react.bridge.ReadableMap.getString(java.lang.String)' on a null object reference.
Here is my code snippet with fetch function:
export const fetchAllUsers = () => {
fetch('http://192.168.1.103:3000/api/userData')
.then(res => {
res.json();
//console.warn('res keys = ' + Object.keys(res))
})
}
If comment back the row with console.warn I see the following "res keys = type, status, ok, statusText, headers, url, _bodyInit, _bodyBlod, bodyUsed".
bodyUsed = false
status = 200
type = default
Why I can't convert a response into json format? Or is there any another way to do so?
UPDATE
I've added the second then but I still get the error and the console.warn('res is json') is not running:
export const fetchAllUsers = () => {
fetch('http://192.168.1.103:3000/api/userData')
.then(res => {
res.json();
//console.warn('res keys = ' + Object.keys(res));
})
.then(res => {
console.warn('res is json');
console.warn(res);
})
}
UPDATE_2
I've run fetch function with another url but still got the problem. It seems like .json() causes the error. When I'm trying to console the result of fetch in the first .then() I get json object with type, status etc keys.
export const fetchAllUsers = () => {
fetch(`http://${localIP}:${port}/api/userData`)
//.then(res => res.json())
.then(json => console.warn('JSON: ' + json))
.catch(e => console.warn('ERROR: ' + e))
}
UPDATE_3
Forgot to mention that I'm creating an Android app with React Native. For testing I'm using a physical smartphone. Chrome version there is 73.0.3683.
I've replaced my fetch query with the following:
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json));
But still get the same error.
When I run it in https://jsfiddle.net/ it works. So the reason is hidden inside the code execution on a smartphone.
There must be more context to your problem; see the below snippet. This clearly works.
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => console.log(json));
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!