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-n7b7u.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>
);
}
CodePudding user response:
Couple of issues here.
- Your submit button is not of type submit, so submit method is never called.
- 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(.....
ps. This is not specifically about React, this is how forms work in HTML.
CodePudding user response:
const onSubmit = (e) => {
e.preventDefault()
let params = new URLSearchParams({
solute: solutestate
});
fetch(
`https://fastapi-ihub-n7b7u.ondigitalocean.app/predict_two?${params}`,
{
method: "GET",
content-type : "application/json"
}
)
.then((res) => res.json())
.then((result) => {
setFetchData(result);
});
};