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

unable to fetch a get request and print the output using fetch api

I am using react to get the data from an API using fetch API and print it but i was unable to retrieve data from after doing a fetch request. Here is the codelink. The input should be CC(C)(C)Br and the output is success message

import React, { useState } from "react";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";

export default function App() {
  const [solutestate, setSolutestate] = useState("");
  const [fetchData, setFetchData] = useState("");
  console.log(solutestate);
  console.log(fetchData);

  let params = new URLSearchParams({
    solute: solutestate
  });

  const onSubmit = (e) => {
    fetch(
      `https://fastapi-ihub-n7b7u.ondigitalocean.app/predict_two?${params}`,
      {
        method: "GET"
      }
    )
      .then((res) => res.json())
      .then((result) => {
        setFetchData(result);
      });
  };

  return (
    <div className="App">
      <>
        <form noValidate onSubmit={onSubmit}>
          <div>
            Input: CC(C)(C)Br
            <TextField
              label="Solute"
              variant="outlined"
              onChange={(e) => setSolutestate(e.target.value)}
            />
            <Button variant="contained">Submit</Button>
            <TextField label="Result" variant="outlined" value={fetchData} />
          </div>
        </form>
      </>
    </div>
  );
}

>Solution :

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

Couple of issues here.

  1. Your submit button is not of type submit, so submit method is never called.
  2. You will also want to put a preventDefault() on your submit handler, as the default will reload the page.

so changes are->

<Button type="submit" variant="contained">Submit</Button>

and

const onSubmit = (e) => {
    e.preventDefault();
    fetch(.....

Updated Sandbox

ps. This is not specifically about React, this is how forms work in
HTML.

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