I am a beginner in javascript. local variable let searchquery = e.target.querySelector('input').value;
value is not print in fatch api q=${searchquery}
and print the global variable value let searchquery='';
my output ispizza
{q: "", from: 0, to: 20, more: false, count: 0, …}
let searchquery='';
searchform.addEventListener('submit', (e) => {
e.preventDefault();
let searchquery = e.target.querySelector('input').value;
console.log(searchquery);
fetchAPI(); });
async function fetchAPI() {
const baseurl = `https://api.edamam.com/search?q=${searchquery}&app_id=${app_id}&app_key=${app_key}&to=20`;
You are creating searchquery
variable twice. One outside and 2nd one inside the anonymous function of addEventListener
. Due to this the variable scope is getting reduced and it won't be available in the fetchAPI
method.
You should use it like this -
let searchquery = '';
searchform.addEventListener('submit', (e) => {
e.preventDefault();
searchquery = e.target.querySelector('input').value;
console.log(searchquery);
fetchAPI(searchquery);
});
async function fetchAPI(searchquery) {
const baseurl = `https://api.edamam.com/search?q=${searchquery}&app_id=${app_id}&app_key=${app_key}&to=20`;
}
OR
If you need to create another variable inside submit handler, then pass this variable to fetchAPI
as param while calling this method.
let searchquery = '';
searchform.addEventListener('submit', (e) => {
e.preventDefault();
let searchquery = e.target.querySelector('input').value;
console.log(searchquery);
fetchAPI(searchquery);
});
async function fetchAPI(searchquery) {
const baseurl = `https://api.edamam.com/search?q=${searchquery}&app_id=${app_id}&app_key=${app_key}&to=20`;
}