Search code examples
reactjsuse-state

setState on submit and not onChange


I have a form, where I use the input from the input fields to send to a back-end.

For example, I have a variable looking something like this:

const [data, setData] = useState([])
const [inputField, setInputField] = useState()

Then I have a form that looks something like this:

<form onSubmit={fetchData}>
    <input type="number" value={value} onChange={(e) => setInputField(e.target.value)} />
    <button type="submit">Fetch data</button>
</form>

The fetchData is given by:

function fetchData(e?: any) {
    e?.preventDefault();
    POST("/api", {
      inputField: inputField,
    }).then(async (response) => {
      const json = await response.json();
      setData({
        retrievedData: json.retrievedData,
      });
    });
  }

I have other forms as well, where this onChange updating is good, but for some input fields I don't need it do update/re-render before the actual submit button that triggers the form are clicked.

So how do I update the state of the inputField when the button is clicked, instead of now where it updates every time I write a new character in the input field ?


Solution

  • Try this

    import {useRef } from "react";
    
    export const Temp = () => {
      const inputField = useRef(null);
    
      const onBtnClick = () => {
        alert(inputField?.current?.value);
      };
      return (
        <div>
    
            <input type="text" ref={inputField} />
            <button type="submit" onClick={onBtnClick}>
              Fetch data
            </button>
          </div>
    
      );
    };