In this task we will implement the search functionality for our Dictionary app. The search functionality will allow users to enter a word and retrieve its definition(s) and pronunciation(s) from the Free Dictionary API.
Step 1: Fetch the API data
Open the main.js file and add the following code to fetch the API data:
Run the app using pnpm dev and open the browser console to see the API data logged.
The API response contains the word’s definition, phonetics, synonyms, antonyms, and examples of usage.
Step 2: Understanding the Code
There are three parts to this code:
We define the dictionaryAPI constant with the base URL of the Free Dictionary API.
We create an async function searchWord that takes a word parameter. This function fetches the API data for the given word and returns the data as a JSON object.
We call the searchWord function with the word “hello” and log the data to the console.
We have not seen the async and await keywords before. These are part of the modern JavaScript syntax for handling asynchronous operations. The fetch function returns a Promise that resolves to the Response object representing the response to the request. We use await to pause the execution of the function until the Promise is resolved. This allows us to write asynchronous code that looks synchronous.
The use of the then and catch methods is another way to handle Promise objects. The then method is called when the Promise is resolved, and the catch method is called when the Promise is rejected (i.e., an error occurs).
We will explore these concepts further in the lecture notes associated with this tutorial lesson on Asynchronous Programming in JavaScript. For now, focus on understanding the flow of the code and how we are fetching data from the API.
The try...catch block is a familiar pattern used in error handling in languages like Java and C++. The try block holds the code that could potentially cause an error, while the catch block catches the error and handles it gracefully. In our scenario, we throw a new Error object with a message if the API request fails. This is a typical practice to provide meaningful error messages to the user or developer. I’ve used it in this instance to illustrate how to raise an error.
Step 3: Run Search on User Input
Now, let’s modify the code to run the search when the user enters a word in the input field and clicks the search button. Add this code to the main.js file:
In the code above, we select the input field and the submit button using document.getElementById. We then add an event listener to the submit button that triggers the search when clicked. The search function is called with the word entered by the user. The API data is logged to the console for now.
Run the app using pnpm dev and test the search functionality by entering a word in the input field and clicking the search button.
Step 4: Extract the Word’s Definitions
Next, we will extract the word’s definition from the the API data and display it in the console. Add the following code to the main.js file:
The extractWordDefinitions function takes the API data as input and extracts the word’s part of speech and definitions. We check if the data is an array and if it contains the necessary properties before extracting the information. This is called defensive programming, where we check for the existence of properties before accessing them to avoid errors. We then loop through the meanings and log the part of speech and definitions to the console.
Modify the then block in the event listener to call the extractWordDefinitions function:
Run the app using pnpm dev and test the search functionality. Try searching for “asynchronous” and check the console for the extracted word definition. You should see “adjective” as the part of speech and three definitions for the word “asynchronous” when it is used as an adjective.
Step 5: Display the Word’s Definitions
Now that we have extracted the word’s definitions, let’s display them in the browser. We will create a section element to hold the definitions and append it to the main section. Add the following code to the main.js file:
In the above code, we define the displayWordDefinition function that takes an array of meanings as input. We first clear the existing content of the definitions section. We then create a header element for the definitions section and append it to the section. For each meaning, we create a div element to hold the part of speech and definitions. We create a p element for the part of speech and a ul element for the definitions. We loop through the definitions and create a li element for each definition, appending it to the ul element.
Next, update the extractWordDefinitions function to return the meanings array:
Finally, modify the then block in the event listener to call the displayWordDefinition function:
Run the app using pnpm dev and test the search functionality. Enter a word in the input field and click the search button. You should see the word’s definitions displayed in the browser.
Step 6: Refactor the Code
Let’s refactor the displayWordDefinition function to make it more modular and readable. Replace the existing displayWordDefinition function with the following code:
In the refactored code, we have broken down the displayWordDefinition function into smaller, more focused functions. Each function is responsible for creating a specific part of the UI element. This makes the code more modular, easier to read, and maintainable.
Step 7: Extract the Word’s Phonetics
Next, let’s extract the word’s phonetics from the API data and log them to the console. Add the following code to the main.js file:
The extractWordPhonetics function takes the API data as input and extracts the word’s phonetics. We check if the data is an array and if it contains the necessary properties before extracting the information. We then loop through the phonetics and log the text and audio to the console.
Modify the then block in the event listener to call the extractWordPhonetics function:
Run the app using pnpm dev and test the search functionality. Enter a word in the input field and click the search button. You should see the word’s phonetics displayed in the console.
Step 8: Display the Word’s Phonetics
Now that we have extracted the word’s phonetics, let’s display them in the browser. Add the following code to the main.js file:
In the above code, we define the displayWordPhonetic function that takes an array of phonetics as input. We first clear the existing content of the phonetics section. We then create a header element for the phonetics section and append it to the section. For each phonetic, we create a div element to hold the text and audio. We create a p element for the phonetic text and an audio element for the audio. We set the source of the audio element to the audio URL.
Next, update the extractWordPhonetics function to return the phonetics array:
Finally, modify the then block in the event listener to call the displayWordPhonetic function:
Run the app using pnpm dev and test the search functionality. Enter a word in the input field and click the search button. You should see the word’s phonetics displayed in the browser.
Step 9: Refactor the Code
Let’s refactor the displayWordPhonetic function to make it more modular and readable. Replace the existing displayWordPhonetic function with the following code:
In the refactored code, we have broken down the displayWordPhonetic function into smaller, more focused functions. Each function is responsible for creating a specific part of the UI element. This makes the code more modular, easier to read, and maintainable.
Step 10: Putting It All Together
Here is the final version of the main.js file with the search functionality, word definitions, and phonetics implemented:
Now that we have implemented the search functionality, extracted and displayed the word’s definitions and phonetics, and refactored the code for readability, run the app using pnpm dev and test the search functionality. Enter a word in the input field and click the search button. You should see the word’s definitions and phonetics displayed in the browser.