2

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.

digitai
  • 1,870
  • 2
  • 20
  • 37
  • Can you log the JSON response to see if your getting a number back? – user2085143 Feb 24 '17 at 17:18
  • In your example, you do not assign any value to the "response" variable, which is then assigned to this.number, so the value is undefined. Please provide your full code if this is not the issue – Scalpweb Feb 24 '17 at 17:18
  • The response is a json string, exactly like this "32250", it's the output of an API. – digitai Feb 24 '17 at 17:36
  • Please include the fetch api code so, it's easier to obtain the context/perspective from which you are utilizing this callback. – Michael Stilson Feb 24 '17 at 19:16
  • your (first) console.log is not logging the correct value, because `fetch` is asynchronous, and you're trying to log the value before it's been fetched. – Heretic Monkey Feb 24 '17 at 19:35

1 Answers1

0

Contents of: data/example-fetch-1.json

{
  "foo": "Hello",
  "bar": "World"
}

Contents of: data/example-fetch-1.json

{
  "foo": "Be",
  "bar": "Yah"
}

Class definition, usage:

'use strict';
class jsonData {
    constructor(url) {
        let thisObject = this;
        thisObject.dataJson = null;
        thisObject.dataUrl = url;
        thisObject.fetchData = function (url) {
            if (!!url) {
                thisObject.dataUrl = url;
            }
            fetch(thisObject.dataUrl, {
                method: 'GET'
            }).then(function (fetchResponse) {
                return fetchResponse.json();
            }).then(function (fetchResponseJson) {
                thisObject.postProcess(fetchResponseJson);
            }).catch(function (doh) {
                throw new Error(doh);
            });
        }
        thisObject.message = function () {
            let bar = 'DOH';
            let foo = 'doh';
            let jsonDataExists = !!thisObject.dataJson;
            if (jsonDataExists) {
                let incomingData = thisObject.dataJson;
                bar = incomingData.bar || bar;
                foo = incomingData.foo || foo;
            }
            return foo+' '+bar+'!';
        }
        thisObject.postProcess = function (responseJson) {
            thisObject.dataJson = responseJson;
            console.log('jsonData.message() = ', thisObject.message());
        }
    }
}
var jsonDataGetter = new jsonData('data/example-fetch-1.json');
jsonDataGetter.fetchData();
jsonDataGetter.fetchData('data/example-fetch-2.json');
Michael Stilson
  • 340
  • 2
  • 10
  • Using this code, gives me always the '43090' value, instead of the response value. – digitai Feb 24 '17 at 17:42
  • So, you are looking to just have a callback function return whatever value response is? – Michael Stilson Feb 24 '17 at 18:14
  • Yes, I need to expose the value of response as a variable which can be accessed by other functions. I fetch a json encoded strign from an API, gives me responses like "41087", need to expose this value, which changes everytime it is fetched. The function value() is invoked by the fetch method and receives as parameter the fetch response. – digitai Feb 24 '17 at 18:46