|
| 1 | +// Formats response to look presentable on webpage |
| 2 | +const renderResponse = (res) => { |
| 3 | + // handles if res is falsey |
| 4 | + if(!res){ |
| 5 | + console.log(res.status) |
| 6 | + } |
| 7 | + // in case res comes back as a blank array |
| 8 | + if(!res.length){ |
| 9 | + responseField.innerHTML = "<p>Try again!</p><p>There were no suggestions found!</p>" |
| 10 | + return |
| 11 | + } |
| 12 | + |
| 13 | + // creating an array to contain the HTML strings |
| 14 | + let wordList = [] |
| 15 | + // looping through the response and maxxing out at 10 |
| 16 | + for(let i = 0; i < Math.min(res.length, 10); i++){ |
| 17 | + // creating a list of words |
| 18 | + wordList.push(`<li>${res[i].word}</li>`) |
| 19 | + } |
| 20 | + // joins the array of HTML strings into one string |
| 21 | + wordList = wordList.join("") |
| 22 | + |
| 23 | + // manipulates responseField to render the modified response |
| 24 | + responseField.innerHTML = `<p>You might be interested in:</p><ol>${wordList}</ol>` |
| 25 | + return |
| 26 | +} |
| 27 | + |
| 28 | +// Renders response before it is modified |
| 29 | +const renderRawResponse = (res) => { |
| 30 | + // taking the first 10 words from res |
| 31 | + let trimmedResponse = res.slice(0, 10) |
| 32 | + //manipulates responseField to render the unformatted response |
| 33 | + responseField.innerHTML = `<text>${JSON.stringify(trimmedResponse)}</text>` |
| 34 | +} |
| 35 | + |
| 36 | +// Renders the JSON that was returned when the Promise from fetch resolves. |
| 37 | +const renderJsonResponse = (res) => { |
| 38 | + // creating an empty object to store the JSON in key-value pairs |
| 39 | + let rawJson = {} |
| 40 | + for(let key in response){ |
| 41 | + rawJson[key] = response[key] |
| 42 | + } |
| 43 | + // converting JSON into a string and adding line breaks to make it easier to read |
| 44 | + rawJson = JSON.stringify(rawJson).replace(/,/g, ", \n") |
| 45 | + // manipulates responseField to show the returned JSON. |
| 46 | + responseField.innerHTML = `<pre>${rawJson}</pre>` |
| 47 | +} |
0 commit comments