Fetch data to variable [duplicate] - javascript

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

Related

React/Javascript - TypeError: Cannot read properties of undefined (reading 'json')

React & Javascript noob here, I'm trying to build my first React project. What I want to do is to have a button that fetches automatically the last matches I played on a game. I'm using a API that, when called correctly, returns this json:
{data:
[{id: 0, internal_id: "_map_id_halo1_pillar_of_autumn", name: "The Pillar Of Autumn"},
…]}
I want to extract the name for each object of data and display an unordered list below the button.
But when I click the button, the browser displays the error:
TypeError: Cannot read properties of undefined (reading 'json')
The code that does what I mentioned is as follows:
async fetchHaloMaps()
{
const url = 'https://cryptum.halodotapi.com/games/hmcc/metadata/maps'
const mapNames = [];
fetch(url, {
"method": 'GET',
"headers": {
'Content-Type': 'application/json',
'Cryptum-API-Version': '2.3-alpha',
'Authorization': 'Cryptum-Token XXX'
}
})
.then(response => {
console.log(response);
if (!response.ok)
throw new Error("Response not ok!");
})
.then(response =>
response.json())
.then(data => {
const i=0;
for (const d of data)
{
mapNames[i] = d.name;
i++;
}
this.setState((state, props) => ({
numberOfMaps : i
}));
})
.catch(error => {
console.log("There was an error: " + error);
});
}
I think I'm "parsing" the JSON in the wrong way. But in the JSON, data i indeed an array with a "name" attribute. So I wanted to cycle the data array and copy the attribute "name", but the code above is not working.
I know the HTTP request with fetch does succeed, since in the console.log I can see the response object and it has the 200 OK field, and I can see the JSON associated with the browser developer tools.
You did not return anything from this .then:
.then(response => {
console.log(response);
if (!response.ok)
throw new Error("Response not ok!");
})
so there is no value that gets passed along to the next .then.
While you could do return response, a better approach would be to remove the intermediate .then entirely - only insert a .then when you need to wait for something asynchronous. At the time you get the response, you can check if it's OK and then return the .json(), without waiting in between.
.then(response => {
if (!response.ok) {
throw new Error("Response not ok!");
}
return response.json();
})
.then(data => {

React get image from api using fetch

I need to get an image using the fetch api. My colleague said that the call to the server should return a base64 string to display the image. The image needs to be authenticated and I cant just use its url. This is what I have:
fetch(`${apiUrl}filestore/${logo.name}`, {
.then(res => console.log(res)
Im not really sure how to get the base64 string. Apparantly im not using fetch right. Here is what is displayed in the console,
![screenshot image][1]
Try to format the res to json. Then check the res.
fetch(`${apiUrl}filestore/${logo.name}`, {
method: 'GET',
headers: {
Authorization: JSON.parse(localStorage.getItem('Hidden'))
? `Bearer ${JSON.parse(localStorage.getItem('Hidden')).access_token}`
: '',
},
})
.then(res => return res.json())
.then(res => console.log(res))
Here is the Link to mdn documentation for Fetch API - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("error", e);
considering your response is of JSON type - Link to find the supported body instances - https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Body
Try console.log(typeof response); to find out what your response type is so you can set the body instance in .then(response => response.json() or response.text() etc.,)
Make sure you catch the error too.

How to store data in a variable in the .then() statement of a fetch statement?

I have been trying to think of a way to store the data received in Line 1 (mentioned in comments) in to a variable that I can modify later on.
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
fetch("https://api.covid19api.com/live/country/south-africa", requestOptions)
.then(response => response.text())
.then(result => console.log(result)) //Line 1
.catch(error => console.log('error', error));
You can store responses to another variable like this.
but You should use that with async/await because fetch() is async.
var requestOptions = {
method: 'GET',
redirect: 'follow'
};
async function fetchData(){
const response = await fetch("https://api.covid19api.com/live/country/south-africa", requestOptions)
.then(response => response.text())
.then(result => { return result }) //Line 1
.catch(error => console.log('error', error));
//console.log(response); //store in response.
}
fetchData();

fetch().then() return content-type and body [duplicate]

This question already has answers here:
How do I access previous promise results in a .then() chain?
(17 answers)
Closed 4 years ago.
Every fetch API example on the internet shows how to return only the body using response.json(), response.blob() etc.
What I need is to call a function with both the content-type and the body as a blob and I cannot figure out how to do it.
fetch("url to an image of unknown type")
.then((response) => {
return {
contentType: response.headers.get("Content-Type"),
raw: response.blob()
})
.then((data) => {
imageHandler(data.contentType, data.raw);
});
This obviously doesn't work: data.contentType is filled, but data.raw is a promise. How can I get both values in the same context?
You could write it that way:
fetch("url to an image of unknown type")
.then(response => {
return response.blob().then(blob => {
return {
contentType: response.headers.get("Content-Type"),
raw: blob
}
})
})
.then(data => {
imageHandler(data.contentType, data.raw);
});
Or this way
fetch("url to an image of unknown type")
.then(response => {
return response.blob().then(blob => {
imageHandler(response.headers.get("Content-Type"), blob)
})
})
In both cases you keep the callback in which you receive the resolved blob within the scope where you have access to response.
If you are allowed to use async functions the best solution is to use async/await
async function fetchData() {
const res = await fetch('url');
const contentType = res.headers.get('Content-Type');
const raw = await res.blob();
// you have raw data and content-type
imageHandler(contentType, raw);
}
If not:
fetch('')
.then((res) => res.blob().then((raw) => {
return { contentType: res.headers.get('Content-Type'), raw };
}))
.then((data) => {
imageHandler(data.contentType, data.raw);
});
Wait for the blob then create the object :
fetch("url to an image of unknown type")
.then(response => {
return response.blob()
.then(raw => ({
contentType: response.headers.get("Content-Type"),
raw
}));
).then(data => imageHandler(
data.contentType,
data.raw
));

Using fetch to get data from an API in React

In Panel.js how can I get data from an API that I wrote in index.js?
Panel.js
index.js
ProfilePanel.js
You can use javascript fetch API
GET example
fetch(`https://jsonplaceholder.typicode.com/posts?key=${key}&results=${results}`)
.then((res) => { return res.json() })
.then((data) => {
console.log(data)
});
})
}
POST example
let key = 'key'
let results = 12;
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers : new Headers(),
body:JSON.stringify({key: key, results: results})//use property short hand here
}).then((res) => res.json())
.then((data) => console.log(data))
.catch((err)=>console.log(err))
you already get the response and you map the response to state 'results'.you can dispaly the data by simply writing "this.state.results"

Categories