Ryuk
Ryuk

Reputation: 372

Page reloads after setting state and instead of new state it goes back to initial state

I am having an issue whenever I click on add button it should generate new field and update state. but as soon as I hit Add button it set the new state and adds the field but then it renders again and goes back to the initial state automatically. What I am doing wrong.

Refer to the code link below

https://codesandbox.io/s/react-hooks-usestate-1h8cw?file=/src/index.js

Upvotes: 0

Views: 27

Answers (1)

Anh Tuan
Anh Tuan

Reputation: 1143

  const handleAddInput = (e) => {
    e.preventDefault()
    setContacts([...Contacts, { service: "", contact: "" }]);
    // const list = [...Contacts];
    // list.push({ service: "", contact: "" });
    // setContacts(list);
  };

because your button submit the form . Add e.preventDefault() to prevent it

Upvotes: 1

Related Questions