Home > Mobile >  Prevent function from running when a variable changes in React
Prevent function from running when a variable changes in React

Time:07-19

I have a form with a checkbox and text input.

const [formVars, setFormVars] = useState<any>({checkbox:true})
const submitForm = () => {
  console.log({formVars})
}

render (
  <Checkbox checked={formVars.checkbox} /> Bake the cookies?
  <TextInput label="what kind of cookies?" />
  <Button onClick={() => submitForm()}
)

submitForm should not run until the user clicks submit, however my code seems to be producing a never-ending loop where the form changes formVars, and the change sets off submitForm. How can I prevent this?

CodePudding user response:

There are a bunch of typos in the question, so I created a simple copy of your code.

The button's onClick prop takes a callback, not a function call. You're likely calling the submit function instead of passing it to the button onClick prop.

Here's how you trigger the submission manually for controlled inputs

export default function App() {
  const [formVars, setFormVars] = useState({ checkbox: true });
  const submitForm = (e) => {
    console.log({ formVars });
  };
  const handleChange = (e) => {
    setFormVars(e.target.value);
  };

  return (
    <>
      <label>
        Name:
        <input onChange={handleChange} type="text" name="name" />
      </label>
      <button onClick={submitForm}>submit</button>
    </>
  );
}

CodePudding user response:

<Button onClick={()=> submitForm}

Try this syntax for the button

  • Related