Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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) => {
    setImg(e.target.value);
  };

  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">
              <input
                className="col-3 form-control-sm py-1 fs-4 text-capitalize border border-3 border-dark"
                type="text"
                placeholder="Search Anything..."
                value={img}
                onChange={handleSearchChange}
              />
              ;
            </div>
          </div>
          <div className="row">
            <div className="col-12 d-flex justify-content-evenly flex-wrap">
              {response.results.map((val) => {
                return (
                  <img
                    key={val.id}
                    className="col-3 img-fluid img-thumbnail"
                    src={val.urls.small}
                    alt="val.alt_description"
                  />
                );
              })}
            </div>
            ;
          </div>
        </>
      ) : (
        // Other div with default values gotten from default api url
      )}
    </div>
  );

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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`
}
//then...
useFetch(getUrl(img))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading