In the previous exercise, we walked through the boilerplate code for making a GET request using async
and await
.
In this exercise, we’re going to apply the code to get nouns that describe the inputted word using the Datamuse API.
Instructions
Under the comment “Asynchronous function”, create a const
variable called getSuggestions
and set it to a new arrow function using the async
keyword.
You’ll be coding inside the getSuggestions()
function for the remainder of this exercise.
Inside the getSuggestions()
function, create a const
variable named wordQuery
and assign it inputField.value
.
Create another const
variable called endpoint
and assign it the value of a string that is url
, queryParams
, and wordQuery
concatenated in that order.
Add a try
statement with an empty code block. Outside the code block for try
, add a catch(error)
statement with a code block that logs error
to the console.
Inside the try
code block, create a const
variable named response
and assign it to await
the result of calling fetch()
with endpoint
as the first argument. For this API to work within the Codecademy browser, add {cache: 'no-cache'}
as the second argument.
Below the response
variable declaration from the previous step, create a conditional statement that the checks if the ok
property of the response
evaluates to a truthy value.
Inside the code block of the conditional statement, await
response.json()
and save it to a new const
variable called jsonResponse
.
Still inside the conditional statement, call the function renderResponse()
and pass in jsonResponse
. Then, run the code.
In the input field, type in a word and click the submit button on the web page.
Great, now we have an organized list of words from the GET request!
The declaration of the renderResponse()
function can be found at public/helperFunctions.js.