I am working on my very first javascript application (a dictionary app) and I am having trouble using try / catch. The try block seems to work with no problems and I can search for words in the API, however the error does not work.
When searching for a word that does not exist, there should be an error message instead of the search result, but this is not appearing. Instead, the data still seems to be getting returned from the function fetchData()
and passed into the subsequent function displayData()
and causing the error.
I might be incorrect here, but shouldn’t the catch block prevent the return statement from the try block from being executed? I have tried adding return
to the catch block to see if it would change anything, but I’m out of my depth here and can’t find a solution. Can anyone help point me in the right direction?
Here is a jsfiddle: https://jsfiddle.net/trpxL0kj/
Here is my code:
const url = "https://api.dictionaryapi.dev/api/v2/entries/en/";
const form = document.querySelector('.form');
const input = document.querySelector('.form-input');
const content = document.querySelector('.content');
const details = document.querySelector('.details');
const fetchData = async () => {
let inputWord = document.querySelector('.form-input').value;
try {
const response = await fetch(`${url}${inputWord}`);
const data = await response.json();
console.log(data);
return data;
} catch (error) {
details.innerHTML = 'This word is not in the dictionary.';
}
};
const displayData = async (entry) => {
const word = entry[0].word;
const grammar = entry[0].meanings[0].partOfSpeech;
const definition = entry[0].meanings[0].definitions[0].definition;
const example = entry[0].meanings[0].definitions[0].example || '';
details.innerHTML = `
<article class="result">
<p class="word">${word}</p>
<p class="grammar">${grammar}</p>
<p class="definition">${definition}</p>
<p class="example">${example}</p>
</article>
`;
};
form.addEventListener('submit', async (e) => {
e.preventDefault();
const data = await fetchData(url);
displayData(data);
});