1

So I want to build a very simple web app where the user enters some text and a paragraph is then created from the same text. Each word in the paragraph is inside a span tag so when the user hovers over it, synonyms of that word are displayed on the console.

I'm pretty sure the part of the code that causes the problem is this :

var lookupLink;
var data;
function preload(){
    lookupLink = 'https://api.datamuse.com/words?ml=';
}
function changeWord(){
    data = loadJSON(lookupLink+this.html())
    var index = floor(random((Object.keys(data).length)));
    console.log(data[index].word);
    //the above console.log gives an error.
}

here's the full code just in case : https://pastebin.com/ViNZ1jse

Instead of logging the word , it shows :

Uncaught TypeError: Cannot read property 'word' of undefined
    at p5.Element.changeWord (sketch.js:39)

I'm guessing this is because the data object hasn't finished loading yet when I try to log one of it's properties , but I don't know how I can work around this. EDIT : Oh and I forgot to mention There's also another issue where I can load the data from https://api.datamuse.com/words?ml= link but not https://api.datamuse.com/words?rel_syn=link.

rain1
  • 27
  • 7

1 Answers1

1

https://p5js.org/reference/#/p5/loadJSON

loadJson can receive a callback that will be executed when your json is loaded. So I assume this will working :

loadJSON(lookupLink+this.html(), function(data) {
  var index = floor(random((Object.keys(data).length)));
  console.log(data[index].word);
})
Julien
  • 832
  • 7
  • 15
  • 1
    Thanks a bunch ! It works perfectly ! if you don't mind me asking, there is also another issue where `https://api.datamuse.com/words?ml=` works but `https://api.datamuse.com/words?rel_syn=` does not. Right now it only prints related words and not synonyms. I tried using the loadJSON and adding a 'jsonp' arguement at the end but that doesn't seem to work either. – rain1 Jun 21 '19 at 11:10