Search code examples
reactjsreact-state-managementreact-state

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


Solution

  •   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