Learn
Requests II
fetch() GET Requests III

In the previous exercise, you wrote the boilerplate code for a GET request using fetch() and .then(). In this exercise, you’re going to use that code and manipulate it to access the Datamuse API and render information in the browser.

If the request is successful, you’ll get back an array of words that sound like the word you typed into the input field.

You may get some errors as you complete each step. This is because sometimes we’ve split a single step into one or more steps to make it easier to follow. By the end, you should be receiving no errors.

Instructions

1.

At the top of main.js, create a const called url. Assign url to the following URL as a string:

https://api.datamuse.com/words
2.

Below url, create another const and call it queryParams. Assign it a value of '?sl='

queryParams will be the start of your query string and will narrow your search to words that sounds like your word.

3.

Inside the getSuggestions() function, create a const called wordQuery and assign it inputField.value.

You’ll need wordQuery to store the value of what is being typed into the input field.

You will be working inside getSuggestions() for the remainder of this exercise.

4.

Now it’s time to add a query string to the URL with all the necessary parameters.

Create another const called endpoint, assign it value of a string that is url, queryParams, and wordQuery concatenated in that order.

5.

Call the fetch() function and pass in endpoint as an argument. For this API to work within the provided browser, add {cache: 'no-cache'} as the second argument.

6.

Chain a .then() method to the fetch() function. Pass it a success arrow callback function as an argument. The callback function should take response as its single parameter.

7.

Inside the success callback function, create a conditional statement that checks if the ok property of the response object evaluates to a truthy value. If so, call the function renderJsonResponse() and pass in response as an argument. Then, run your code.

Then type in a word to and click the submit button to view the JSON that came back. The status of the promise return from fetch() will be resolved.

The code for renderJsonResponse() can be viewed at public/helperFunctions.js.

8.

Delete renderJsonResponse(response) and replace it with return response.json().

By returning response.json(), the next function that is .then() chained to it will receive a Promise with JSON data.

9.

Below the condition’s code block, add this code to raise an exception if the request failed: throw new Error('Request failed!');

10.

Separate the success callback function and the error callback function with a comma. The error callback function will also be an arrow function that takes one parameter, networkError. In the code block of the arrow function, log networkError.message to the console.

Folder Icon

Take this course for free

Already have an account?