Home > Blockchain >  How to do bring predictions from rest api using fetch in react js
How to do bring predictions from rest api using fetch in react js

Time:11-11

I am building an app where the flask rest API takes two strings and gives a floating value as a prediction. Now I am trying to connect to the react app so that the predictions can be shown on a webpage.

Goal: takes two strings from the frontend and does inference using restapi and gives the values of the prediction on the front end.

Below is the code used to fetch the rest API predictions in react app.

function App() {
  const [state, setState] = useState([{}]);

  useEffect(() => {
    fetch("/predict?solute=CC(C)(C)Br&solvent=CC(C)(C)O")
      .then((res) => res.json())
      .then((data) => {
        setState(data);
        console.log(data);
      });
  }, []);

In fetch /predict?solute=CC(C)(C)Br&solvent=CC(C)(C)O here solute=CC(C)(C)Br and solvent=CC(C)(C)O are the inputs for the flask rest API to give predictions.

But I want to give it from the frontend rather than mentioned in the URL. How to do it?

Modified code to fetch results and display

function App() {
  const [state, setState] = useState([{}]);
  const [uri, setUri] = useState([{}]);
  const [resultstate, setResultState] = useState([{}]);

  function HandleSubmit() {
    const uri = "http://127.0.0.1:3000/?${form.one}&${form.two}";
    setUri(uri);
    useEffect(() => {
      fetch(uri)
        .then((response) => {
          if (response.status === 200) {
            return response.json();
          }
        })
        .then((data) => {
          setResultState(data);
          console.log(data);
        });
    });
  }

  function handleChange(e) {
    const { nodeName, name, value } = e.target;
    if (nodeName === "INPUT") {
      setState({ ...FormData, [name]: value });
    }
  }

  return (
    <div className="App">
      <state onChange={handleChange}>
        <fieldset>
          <legend>Solute</legend>
          <input name="one" value={state.one} />
        </fieldset>
        <fieldset>
          <legend>Solvent</legend>
          <input name="two" value={state.two} />
        </fieldset>
        <button type="button" onClick={HandleSubmit}>
          Submit
        </button>
      </state>
      <Deploy />
    </div>
  );
}

Running the modified code I am getting this error enter image description here

CodePudding user response:

  1. Create a new form state.

  2. Create a form with some input elements, and a button to submit the form.

  3. When the input elements are changed update the form state with their values.

  4. When the form is submitted create a new URI with the information in form, and then do the fetch.

const { useState } = React;

function Example() {

  const [ form, setForm ] = useState({});

  function handleSubmit() {
    const uri = `http://example.com/?${form.one}&${form.two}`;
    console.log(`Current state: ${JSON.stringify(form)}`);
    console.log(`Fetch URI: ${uri}`);
    // fetch(uri)... etc
  }

  // Because the listener is attached to the form element
  // (see "Additional documentation" below)
  // check that the element that's been changed is an input
  // and then update the state object using the name as a key, and
  // adding the value of the input as the object value for that key
  function handleChange(e) {
    const { nodeName, name, value } = e.target;
    if (nodeName === 'INPUT') {
      setForm({ ...form, [name]: value });
    }
  }

  // Each input has a name, and maintains its
  // value from the form state
  return (
    <form onChange={handleChange}>
      <fieldset>
        <legend>Input one</legend>
        <input name="one" value={form.one} />
      </fieldset>
      <fieldset>
        <legend>Input two</legend>
        <input name="two" value={form.two} />
      </fieldset>
      <button type="button" onClick={handleSubmit}>Submit</button>
    </form>
  );
};

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Additional documentation

  • Event delegation - that's what's happening when we attach one listener to the form rather than listeners to all the inputs. The form catches the events from the inputs as they bubble up the DOM. But it's also why we need to identify what element they are, hence the need for nodeName.

  • Destructuring assignment

  • Related