Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

155
Vistas
How do make an api fetch request on button click Reactjs?

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; 
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

  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;
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda