Home > Enterprise >  How do make an api fetch request on button click Reactjs?
How do make an api fetch request on button click Reactjs?

Time:10-29

My code so far... I'm trying to have a text box and dropdown list of year that when i click the search button passes 2 parameters into a fetch api request. ive loaded the years into the dropdon box and have a full lst of item names which i will later turn into an auto complete style search box. but for now i just want to send the 2 selected peices of data to a fetch api request where the name of the item is required and the year is optional. i want to populate the itemList array with the data from the fetch request.

const App = () => {
  const [YearList, setYearsData] = useState([]);
  const [NamesList, setNameData] = useState([]);

  //Get YearsList data to populate dropbox

  useEffect(() => {
    const fetchItemData = async () => {
      try {
        fetch("http://localhost:56384/api/YearList")
        .then(response => response.json())
        .then(itemData => setYearsData(itemData));
      } catch(error) {
        console.log("Failed to fetch from Amazon DB", error);
      }
    };
    fetchItemData()
  }, []);
 
  //Get NamesList Data for autocomplete textbox
  useEffect(() => {
    const fetchItemData = async () => {
      try {
        fetch("http://localhost:56384/api/NameList")
        .then(response => response.json())
        .then(itemData => setNameData(itemData));
      } catch(error) {
        console.log("Failed to fetch from Amazon DB", error);
      }
    };
    fetchItemData()
  }, []);
  
  let [year, setYear] = useState(null)
  let handleYearChange = (e) => {
    setYear(e.target.value)
  }

  let [searchQuery, setSearchQuery] = useState("")
  let handleSearchChange = (e) => {
    setSearchQuery(e.target.value)
  }
 //Fetch reqiest that is not working
  const [itemList, setItemList] = useState([]);
    useEffect(() => {
      const fetchItemData = async () => {
        try {
          fetch(`http://localhost:56384/api/RecallSearch?searchText=${searchQuery}&year=${year}`)
          .then(response => response.json())
          .then(itemData => console.log(itemData));
        } catch(error) {
          console.log("Failed to fetch from Amazon DB", error);
        }
      };
      fetchItemData()
    }, []);
  return (
    <div className="App">
      <TitleCard /> 
      <input
      type="text"
      value={searchQuery}
      onChange={handleSearchChange}
      placeholder='Search Amazon Items'/>
      <select onChange={handleYearChange}> 
      <option value="-- Select year --"> -- Select a Year -- </option>
         {YearList.map((year) => <option key={year} value={year}>{year}</option>)}
    </select>
//Button that isnt working
    <button>Search</button>  
    </div>
  );
  
}

export default App; 

CodePudding user response:

  1. You are using async await functions incorrectly
  2. You can simplify your code and use a single useEffect call
  3. You should add an onClick listener to the button

Try to change your code like this:

const App = () => {
  const [YearList, setYearsData] = useState([]);
  const [NamesList, setNameData] = useState([]);
  const [itemList, setItemList] = useState([]);

  let [year, setYear] = useState(null);
  let handleYearChange = (e) => {
    setYear(e.target.value);
  };

  let [searchQuery, setSearchQuery] = useState('');
  let handleSearchChange = (e) => {
    setSearchQuery(e.target.value);
  };

  let [year, setYear] = useState(null);
  let handleYearChange = (e) => {
    setYear(e.target.value);
  };

  let [searchQuery, setSearchQuery] = useState('');
  let handleSearchChange = (e) => {
    setSearchQuery(e.target.value);
  };

  const fetchYearList = async () => {
    try {
      const response = await fetch('http://localhost:56384/api/YearList');
      setYearsData(await response.json());
    } catch (error) {
      console.log('Failed to fetch from Amazon DB', error);
    }
  };

  const fetchNameList = async () => {
    try {
      const response = await fetch('http://localhost:56384/api/NameList');
      setNameData(await response.json());
    } catch (error) {
      console.log('Failed to fetch from Amazon DB', error);
    }
  };

  const fetchItemData = async () => {
    try {
      const response = await fetch(
        `http://localhost:56384/api/RecallSearch?searchText=${searchQuery}&year=${year}`
      );
      const itemData = await response.json();
      setItemList(itemData);
    } catch (error) {
      console.log('Failed to fetch from Amazon DB', error);
    }
  };

  const handleSearch = () => {
    fetchItemData();
  };

  useEffect(() => {
    fetchYearList();
    fetchNameList();
    fetchItemData();
  }, []);

  return (
    <div className='App'>
      <TitleCard />
      <input
        type='text'
        value={searchQuery}
        onChange={handleSearchChange}
        placeholder='Search Amazon Items'
      />
      <select onChange={handleYearChange}>
        <option value='-- Select year --'> -- Select a Year -- </option>
        {YearList.map((year) => (
          <option key={year} value={year}>
            {year}
          </option>
        ))}
      </select>
      //Button that isnt working
      <button onClick={handleSearch}>Search</button>
    </div>
  );
};

export default App;
  • Related