vendredi 1 mai 2020

fetch request not working inside of a javascript if statement but is working when called outside of statement

I am working with an api and have made fetch calls successfully. When I call my fetchData function, it calls successfully and shows up on the page.

I want the user to search for a recipe by clicking on a button and then have the recipe show up rather than showing up onload so I put it inside the event handler and a super simple if statement just to test it. When I console.log the if statement, it works fine with the button. Then I added the fetchData function to the if statement but I get back failed to fetch. When I look at the debugger in the console, I get the error TypeError: Cannot read property 'requestContent' of undefined and a 304 Not Modified error

Here's the code:

const search = document.querySelector("#searchBtn");
//event handler
search.addEventListener('click', (e) => {
  //get input text
const userInput = document.querySelector("#input");
let input = userInput.value;  

if(input !== ""){
  fetchData();  //this function works if I put it outside the if and click event handler block but not when it is inside like this.
}else{
  alert("please fill out input fields")
}
})

Any idea on what I should be doing to make this fetch work or another way to handle getting the fetch after clicking the button? Thanks so much

Aucun commentaire:

Enregistrer un commentaire