Home > Software design >  REACT - My onClick function isn't searching through any of the cities from the API
REACT - My onClick function isn't searching through any of the cities from the API

Time:11-26

Here I am simply making a request. The request is successful and return an array of different breweries along with cities plus more info. The useEffect does not set the default search for a new york city, instead I get a the initial array rendered from the first call.

import React, {useState, useEffect} from 'react';
import '../styles/searchPage.css'
import SearchCard from '../components/SearchCard';


const API_URL =  'https://api.openbrewerydb.org/breweries?by_city&per_page';

function SearchPage() {
  const [cards, setCards] = useState([]);
  const [searchTerm, setSearchTerm] = useState('');
  const searchRestaurants = async (city) => {
    const req = await fetch(`${API_URL}&s=${city}`);
    const data = await req.json()
    console.log(data)
    setCards(data)
  }
  useEffect(() => {
    searchRestaurants('new york')
}, [])

Here is how I set up my search. I set the searchTerm onChange event to read the value typed. Inside of my button I have an onClick function which should fire the restaurant search with any search term in it. Instead i'm receiving back the initial array that I get from the first call to api.

return (  
    <div className='search'>
      <h1>Enter a City or Town name</h1>
      <div className='search-container'>
       <input 
        type="text"
        name="search"
        value={searchTerm}
        onChange={(e) => setSearchTerm(e.target.value)}
        onKeyPress={(e) => {
          if (e.key === 'Enter'){
            searchRestaurants(searchTerm);
          }
        }}
        placeholder="Search..." 
        
        />
        <button 
        className='next'
        onClick={()=> searchRestaurants(searchTerm)}
        >Go</button>
        </div>

CodePudding user response:

Checked your code.

And checked API documentation and i found that you using API incorrectly.

I would change API_URL from https://api.openbrewerydb.org/breweries?by_city&per_page to https://api.openbrewerydb.org/

  1. API_URL - Url defined incorrectly,you did assign endpoint url with 2 empty parameters by_city & per_page which are being sent empty.

  2. Now to fix your issue and properly use endpoint URL should be updated. From fetch(${API_URL}&s=${city}); to fetch(${API_URL}/breweries?by_city=${city});

Hope it helps!

  • Related