Skip to content
Advertisement

Unable to pass value from input to fromData in reactjs

I am having a form using react-hook-form and I am updating the input forms using setState but when I am get formData and do a fetch request the value from the input text field is not loading at all.

This is the picture when I update the input text field from setState and do a fetch request enter image description here

This is the picture when I update the input text field from the keyboard and do a fetch request enter image description here

const FirstProject = () => {
  const [solutestate, setSoluteState] = useState("");
  const [solventstate, setSolventState] = useState("");
  const [fetchData, setFetchData] = useState("");
  const [Error, setError] = useState(null);

  const { register, handleSubmit, control } = useForm({
    defaultValues: {
      solute: "",
      solvent: "",
    },
  });

  const formData = new FormData();
  const onSubmit = (data) => {
    formData.set("solute", data.solute);
    formData.set("solvent", data.solvent);

    fetch("https://flask-api-test1.herokuapp.com/predict", {
      method: "post",
      body: formData,
    })
      .then((res) => res.json())
      .then((result) => {
        setFetchData(result.result.predictions);
        //console.log(result.result.predictions);
        //console.log(Object.entries(result));
        // setIsPending(false);
      })
      .catch((err) => {
        console.log(data);
        setError(err.error);
        console.log(err);
      });
  };

<form onSubmit={handleSubmit(onSubmit)}>
 <input
  {...register("solute")}
  placeholder="First Name"
  onChange={(e) => setSoluteState(e.target.value)}
  value={solutestate}
 />
 <input
  {...register("solvent")}
  placeholder="First Name"
  onChange={(e) => setSolventState(e.target.value)}
  value={solventstate}
 />
 <input type="submit" />
 </form>

Advertisement

Answer

So you have a couple of issues I can currently see in the code.The state was the same for the onchange event for both a solvent and solute that why they kept using the same state. You needed to use the other hook you created. The 2nd issue you had was that you were sending the variable FormData instead of data (argument provided to function). The form data was an empty variable the whole time. Here is the correct version.

Fixed below: https://codesandbox.io/s/quirky-tdd-0zs4c?file=/src/App.js

//per the documents handle submit also gives you the Event Object*

handleSubmit: 
((data: Object, e?: Event) => void, (errors: Object, e?: Event) => void) => Function

So your code should be gettin g the input data from the state/event object on change, and when the user submits, trigger the logic to validate and send.

import Editortwo from "./components/Editortwo";
import "./styles.css";
import { useState } from "react";
import { useForm } from "react-hook-form";

export default function App() {
  const [solutestate, setSoluteState] = useState();
  const [solventstate, setSolventState] = useState();

  const [fetchData, setFetchData] = useState("");
  const [Error, setError] = useState(null);

  const { register, handleSubmit } = useForm({
    defaultValues: {
      solute: "",
      solvent: ""
    }
  });

  const onSubmit = async data => {
    let res;
    console.log(" Post Data To send to API", data);
    try {
      res = await fetch("https://flask-api-test1.herokuapp.com/predict", {
        method: "post",
        //this was formData which was blank
        body: JSON.stringify(data)
      });
    } catch (err) {
      res = err;
      setError(err);
      console.log(err);
    }

    if (!res) {
      console.warn("Invalid Response", res.status);
      throw Error("No API Response");
    }

    const json = await res.json();
    console.log("Results from Request", json);
    if (json.result) {
      setFetchData(json.result.predictions);
    }
  };
  return (
    <div className="App">
      <Editor {...{ setSoluteState }} />
      <Editortwo {...{ setSolventState }} />
      <form noValidate onSubmit={handleSubmit(onSubmit)} className="space-x-4">
        <input
          className="shadow appearance-none border rounded  py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
          {...register("solute")}
          placeholder="SOLUTE"
          onChange={(e) => setSoluteState(e.target.value)}
          value={solutestate}
        />
        <input
          className="shadow appearance-none border rounded  py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
          {...register("solvent")}
          placeholder="SOLVENT"
          onChange={(e) => setSolventState(e.target.value)}
          value={solventstate}
        />
        <input
          className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
          type="submit"
        />
        <input
          className="shadow appearance-none border rounded  py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
          type="text"
          readOnly
          value={fetchData}
          name="OUTPUT"
        />
      </form>
    </div>
  );
}

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement