What is the best approach to use different API calls for conditional rendering a React app

I’m trying to set a default url from an api when the user is not searching anything inside the searchbar.
What is the best approach? Here’s the code for a better explanation:

 const [img, setImg] = useState("");

  const defaultUrl `https://api.unsplash.com/search/photos?page=1&query=chefs&client_id=${clientId}&per_page=20`;`
  const url = `https://api.unsplash.com/search/photos?page=1&query=${img}&client_id=${clientId}&per_page=20`;
  const { response, loading, error } = useFetch(url);

  const handleSearchChange = (e) => {

  return (
    <div className="container-fluid">
      {loading && <p>Loading...</p>}
      {error && <p>Something went wrong...</p>}
      {response && response === null ? (
          <div className="row">
            <div className="col-12 d-flex justify-content-center align-items-center input">
                className="col-3 form-control-sm py-1 fs-4 text-capitalize border border-3 border-dark"
                placeholder="Search Anything..."
          <div className="row">
            <div className="col-12 d-flex justify-content-evenly flex-wrap">
              {response.results.map((val) => {
                return (
                    className="col-3 img-fluid img-thumbnail"
      ) : (
        // Other div with default values gotten from default api url

Tried somehow changing the url of the Usefetch call when there was no response. I was thinking about making a seperate component for the images, but not sure how to implement the usefetch then so it is dynamic.

>Solution :

if your useFetch hook reacts to changes, then…

useFetch( img === "" ? defaultUrl : `https://api.unsplash.com/search/photos?page=1&query=${img}&client_id=${clientId}&per_page=20 `

Or for cleaner codes, create a getUrl function

// this outside component so it doesn't recreate on every render
const getUrl = (img) => {
  return `https://api.unsplash.com/search/photos?page=1&query=${img}&client_id=${clientId}&per_page=20`
// then use it this way
useFetch(img === "" ? defaultUrl : getUrl(img))

You can even go one step further by putting the conditional check in getUrl() function

const getUrl = (img) => {
  return img === "" ? default Url : `https://api.unsplash.com/search/photos?page=1&query=${img}&client_id=${clientId}&per_page=20`

Leave a Reply