October 23, 2024
Chicago 12, Melborne City, USA
javascript

Need help understanding how to make fetch request from React frontend to Node backend


I have a fundamental understanding of how my project architecture needs to look based on the resources I am using but I’m getting hung up on implementing specific features to create my MVP. I am working on a project which makes calls to a third-party api (tumblr for anyone wondering) and I have the basics set up and understanding to get the data I want to my Node backend server. Where I’m having trouble is passing that data back to my React frontend to use.

My Node backend currently passes back a single url under "url" in my response json, like so:

app.get("/img", async (req, res) => {
  // Make the request
  var response = await client.taggedPosts(req.tag, { limit: 1 });
  console.log(response[0].post_url);
  res.json({ url: response[0].post_url });
});

where url is a string.

The idea is to then return that url for my frontend to use, which makes a call to the node server when a button is clicked:

function SearchBar() {
  const [resList, setResList] = React.useState(null);
  const FetchAPI = () => {
    if (document.getElementById("search-input").value) {
      console.log("fetching...");
      fetch("/img", { tag: document.getElementById("search-input").value })
        .then((res) => res.json())
        .then((data) => setResList(data.url));
    } else {
      //Pop-up handler to be added?
    }
    if (resList) {
      console.log(resList);
    }
  };

  useEffect(() => {}, []);

  return (
    <span className="SB-span">
      <form>
        <input id="search-input" type="search" placeholder="Search" />
        <button onClick={FetchAPI}>Search</button>
      </form>
    </span>
  );
}

As far as debugging goes I can temporarily see the console outputs that tell me the fetch call is being made though I can’t see any update to resList and the console clears itself in the browser after each call. This is most likely a fundamental misunderstanding on my part but I’m a bit lost as React has so much documentation with numerous solutions to a given problem.

What I’m looking for is to receive one singular url which may be expanded into a list of multiple later on, and to pass that result to another component on the page with the intention of cycling through the results like a slideshow. If more info is needed feel free to let me know and I will answer to the best of my ability.



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video