Fetching data via the Fetch API, I need to assign the response to a variable, which will be used in many instances, like a global value.
The most adequate way to do so is to create an object and assign the fetch response to one of it's properties.
var number = 0;
fetch(url, numberValue); // fetch data from API, returns a string like "5489721"
function numberValue(response) {// invoked by fetch, it's parameter is the fetch response.
this.number = response:
// console,log('number='+this.number): // 43090
}
console.log("number value outside function value="+ new numberValue().number): // prints undefined.
However I found that inside the function that creates the object, the assigned value works well, but if I invoke the object outside it's constructor function I get a value of "undefined".
However if I assign a fixed value, I get the correct value which makes me think that the problem is with the json response, however it works perfectly inside it's constructor.
The fetch function is this:
function fetchGet(url, functionName) {
fetch(url, {
method: 'GET'
}).then(function(response) {
return response.json();
}).then(function(json) {
functionName(json); // here I invoke other function to process response.
}).catch(function(err) {
}
It's invoked on page load, like this:
var url =""; // API endpoint, gives a plain "525554"
fetchGet(url, value);
function value (response) {
console.log('response='+response); //52554
}
However what I need, beyond capturing the plain value, is to expose this value in the namespace which will be used bay other functions.