I am trying to read a value from a response object, but this
fetch("https://api.nft.storage/upload", options)
.then((response) => response.json())
.then((response) => console.log(response))
.then((response) => {
console.log(response.value.cid);
}
... doesn't work. Although my console shows the object being sent:
.. I get this error:
Unhandled Rejection (TypeError): Cannot read properties of undefined (reading 'value')
1056 | .then((response) => response.json())
1057 | .then((response) => console.log(response))
1058 | .then((response) => {
> 1059 | console.log(response.value.cid);
console.log() doesn't return anything, so response in the next .then() is undefined. Just do both in the same function.
fetch("https://api.nft.storage/upload", options)
.then((response) => response.json())
.then((response) => {
console.log(response);
console.log(response.value.cid);
}
}
Related
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 21 days ago.
I'm trying to get data from a API to a variable for Geocoding,I use fetch to get API reponse like this:
` var requestOptions = {
method: 'GET',
};
fetch("https://api.geoapify.com/v1/geocode/search?text=38%20Upper%20Montagu%20Street%2C%20Westminster%20W1H%201LJ%2C%20United%20Kingdom&apiKey=${MYKEYAPI}", requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.then(data=>{jsonData=data;})
.catch(error => console.log('error', error));`
(In my code I use my actual keyAPI)
I need to get the data so I can get the latitude and longitude in the following lines, but because fetch is a promise, I'm unable to add it to a variable. The values appear in browser console.
How can I add it to a variable, I have seen that some people use async I tried this way:
async function fetchText() {
let response = await fetch("https://api.geoapify.com/v1/geocode/search?text=38%20Upper%20Montagu%20Street%2C%20Westminster%20W1H%201LJ%2C%20United%20Kingdom&apiKey=${MYKEYAPI}", requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.then(data=>{jsonData=data;})
.catch(error => console.log('error', error));
let data = await response.text();
console.log(data);
}
fetchText();
But it gives "Uncaught (in promise) TypeError: Cannot read properties of undefined "
My intent with await:
async function funcionAsincrona(){
const responses = await fetch("https://api.geoapify.com/v1/geocode/search?text=38%20Upper%20Montagu%20Street%2C%20Westminster%20W1H%201LJ%2C%20United%20Kingdom&apiKey=${MYKEYAPI}", requestOptions)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log('error', error));
return responses;
}
let responses=funcionAsincrona();
but responses is like this:
Promise {}[[Prototype]]:... "Promise"[[Prototype]]: Object[[PromiseState]]: "fulfilled"[[PromiseResult]]: undefined
How can I make it work?
I may be wrong, but it seems to me that in this
line let data = await response.text();
await is superfluous
I'm using a feth request to recieve data from an API.
This is what my request looks like:
fetch(url, requestOptions)
.then(response => response.json())
.catch(error => colsole.log('error', error);
And I'm trying to figure out how to filter certain values from the response.
Here's what the response looks like:
[
{
'Obj.Name': 'objname1',
'Obj.property': 'red'
...
},
{
'Obj.Name': 'objname1',
'Obj.property': 'blue'
...
},
{
'Obj.Name': 'objname3',
'Obj.property': 'green'
...
},
]
I wanna add another ".then" statement there with a function that gets a parameter like ('Obj.Name') that can filter everything by that particular objectname and be able to get other properties of that object.
I want the result to be something like this:
Obj: objectname1, ObjProp: red
Like this?
fetch(url, requestOptions)
.then(response => response.json())
.then((data) => {
const filtered = data.filter(item => item["Obj.Name"] === "objname1")
console.log(filtered)
})
.catch(error => colsole.log('error', error);
I am fetching data using an API in react native. When fetched data in console, its successfully getting data. But while using the code below, the album array is showing undefined.
state = { albums: [] };
componentWillMount() {
//fetch('https://ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=881262b246e1d3f2abda8771b1a25fe3&format=json')
fetch('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => this.setState({ albums: response.data }));
}
I am getting console logs like this
{albums: Array(0)}
{albums: undefined}
Why this is undefined?
A Response object has no data property. You access the body of the response by calling the text, json, blob, or arrayBuffer methods and consuming the promise they return.
For instance, if you're receiving JSON:
fetch('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => response.json())
.then(data => this.setState({ albums: data }));
Live Example:
fetch('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => response.json())
.then(data => {
console.log(data);
});
Or we could call the parameter albums and use shorthand property notation:
fetch('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => response.json())
.then(albums => this.setState({ albums }));
I need to post something on my API.
I have this function which works correctly:
TradeContainer.js:
callApi(action){
var actionInfo = {
user_id: this.props.currentUser.id,
action: action
}
fetch('http://localhost:3000/actions', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(actionInfo)
})
.then(res => res.json())
.then(data => console.log(data))
}
I want to move fetch() to another file from where i make all API calls. In that file I already have several fetch functions (with get method) and they work fine.
But when I move this fetch() with post method to that file, I get an error:
TypeError: Cannot read property 'then' of undefined
My code:
TradeContainer.js:
import { saveAction } from '../components/apiCalls.js'
callApi(action){
var actionInfo = {
user_id: this.props.currentUser.id,
action: action
}
//this is fetch() function that i moved to apiCalls.js file.
//And this two lines of code throw an error.
saveAction(actionInfo)
.then(data => console.log(data))
}
apiCalls.js
export function saveAction(actionInfo){
fetch('http://localhost:3000/actions', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(actionInfo)
})
.then(res => res.json())
}
.then(res => res.json()) returns "ok" and 200.
but saveAction(actionInfo) returns undefined. How come?
The function saveAction doesn't return anything (specifically - doesn't return promise) so you can't use then on that function:
export function saveAction(actionInfo){
fetch({
...
})
.then(res => res.json())
}
You can return the fetch (which is a promise) and then you can use then on that function:
export function saveAction(actionInfo){
return fetch({
...
})
.then(res => res.json())
}
If it may be of any help for noobs like me,make sure the return and the fetch statement are on the same line, or surround the fetch statement in parenthesis.
Avoid this! it will also cause the Cannot read property 'then' of undefined error.
function fetchData(){
return
fetch(url)
.then(response => response.json())
}
Try this.
function fetchData(){
return (
fetch(url)
.then(response => response.json()))
}
Using react and webpack.. why does the code below result in an error: Uncaught (in promise) SyntaxError: Unexpected end of input(…)? Thanks
fetch(feedURL, {"mode": "no-cors"})
.then(response => response.json())
.then(function(data){
this.setState({
data: data
})
}.bind(this));
To better understand your error, add a catch case to your fetch request.
Also, if you use arrow functions, you don't need to bind(this);
fetch(feedURL, {"mode": "no-cors"})
.then(response => response.json())
.then(data => {
this.setState({
data: data
});
})
.catch(resp => {
console.error(resp);
});