0

//hotels?country_id=searched_country_id
//hotels?city_id=searched_city_id
//hotels?hotel_id=searched_hotel_id


useEffect(() => {
  const idCategory = params.id;
  const idName = params.id;

  fetch(
    `http://10.58.5.162:8000/hotels?${idCategory}=${idName}`
     ,
    {
      method: 'GET',
    }
  )
    .then(res => res.json())
    .then(data => {
      setHotelList(data.message);
    });
}, []);

I want to make fetch for country_id, city_id, and hotel_id but until I get data, I do not know which one. It could be country_id or city_id or hotel_id, but not both. I do not know how to do it so I would appreciate any advice! Thank you in advance.

Apostolos
  • 10,033
  • 5
  • 24
  • 39
dlkhjs
  • 43
  • 4

1 Answers1

0

using react-route-v6 useSearchParams you can get it like here have demo example link

import "./styles.css";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link,
  useSearchParams
} from "react-router-dom";

/**
 * https://stackoverflow.com/questions/70043493/react-router-dom-v6-params
 */

const HotelsComponent = () => {
  const [searchParams] = useSearchParams();
  let queryParams = "";
  if (searchParams.get("country_id")) {
    queryParams = `country_id=${searchParams.get("country_id")}`;
  } else if (searchParams.get("city_id")) {
    queryParams = `city_id=${searchParams.get("city_id")}`;
  } else {
    queryParams = `hotel_id=${searchParams.get("hotel_id")}`;
  }

  return <div>country_id: {queryParams}</div>;
};

export default function App() {
  return (
    <Router>
      <div className="App">
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>

        <ul>
          <li>
            <Link to="/">home</Link>
          </li>
          <li>
            <Link to="/hotels?country_id=123455">
              /hotels?country_id=123455
            </Link>
          </li>
          <li>
            <Link to="/hotels?city_id=123">/hotels?city_id=123</Link>
          </li>
          <li>
            <Link to="/hotels?hotel_id=123">/hotels?hotel_id=123</Link>
          </li>
        </ul>
        <Routes>
          <Route path="/hotels" element={<HotelsComponent />} />
        </Routes>
      </div>
    </Router>
  );
}



Kanti vekariya
  • 667
  • 3
  • 13