Quantcast
Channel: Iterate thru json fetch
Viewing all articles
Browse latest Browse all 21

Iterate thru json fetch

$
0
0

@partylich wrote:

data in your callback functions does contain the return value of the previous step in the chain.
But document.getElementById('kanji').innerHTML = kanji.character doesn’t reference the named parameter data. It tries to set the element’s innerHTML to kanji.character, a variable you haven’t defined.

It might be easier to picture if you extract your callbacks to their own functions. So from this:

to this

/** Parse response object
 * returns object parsed from json
 */
const getJsonFromRes = (res) => res.json();

/**  Logs some data. 
 * returns undefined
 */
const logData = (data) => console.log(data[1].kanji.character);

/** Ignores its data parameter. Attempts to set an element to an uninitialized variable.
 */
const accessMagicVariable = (data) => document.getElementById('kanji').innerHTML = kanji.character;

// print error to console. returns undefined.
const logError = (err) => console.log(err);

myfetch 
  .then(getJsonFromRes) 
  .then(logData) 
  .then(accessMagicVariable) 
  .catch(logError);

Then look at each function individually. The humorously (I hope) named accessMagicVariable is the problem I’m referring to. The blander logData is the problem RandellDawson has noted. logData needs to be rewritten to return the value you’d like to work with in the next part of the chain. accessMagicVariable needs to be rewritten so that it’s statements refer to the actual parameter name the function is receiving.

Hopefully that helps a tiny bit?

*note: my statements about kanji.character being defined in accessMagicVariable are based on the code you’ve provided. If there’s more code in scope at this point that you haven’t shown, I would have no way of knowing that.

Edit: There’s also a handy debugger command you can insert into your code when running in a browser. It will let you step through execution and see the value of variables that are in scope and all sorts of useful things like that. I’m struggling to maintain consciousness, otherwise i’d find a link for you. Sorry

Read full topic


Viewing all articles
Browse latest Browse all 21

Trending Articles