0

I am currently trying to make an application within React that accepts a form. This form contains input fields that the user can type directly into and this will generate a state change in the formInput object:

 const [formInput, updateFormInput] = useState({
    name: "",
    job: "",
    salary: "",
  });


      <input
           placeholder="Name?"
           onChange={(e) =>
             updateFormInput({ ...formInput, name: e.target.value })
           }
          />
     
      <input
        placeholder="Salary?"
        onChange={(e) =>
          updateFormInput({ ...formInput, job: e.target.value })
        }
      />

      <input
        placeholder="Job?"
        onChange={(e) =>
          updateFormInput({ ...formInput, salary: e.target.value })
        }
      />
     

I would now like to introduce an autocomplete feature based on some data, when the user presses the button, I would like that formUptdate object to change to the values of a new object and the auto complete to be represented within the fields on screen.

 <button onClick={() => {
      handleClick();
    }}
  >  
    Autofill
  </button>

 const handleClick = () => {
    updateFormInput({
      ...formInput,
      name: "Me",
      job: "My Job",
      salary: "My Salary",
    });
  };

Above is the new logic I have attempted, however when I click this button it does not trigger the expected results and my input fields remain the same.

Does anyone know why this might be?

Kevin
  • 137
  • 1
  • 12
  • The code must work fine with changing the state. You can test the state by submitting the form after the button is pressed. You problem actually is that the inputs value in the page do not show new values. Just add ```value``` in the inputs reading from ```formInput``` object like this : `````` – Farhad Rad Jul 23 '22 at 08:34

1 Answers1

0

You need to set the value of the input fields. as the input update the state, but the state doesn't update the input

      <input
       placeholder="Name?"
       onChange={(e) =>
         updateFormInput({ ...formInput, name: e.target.value })
         value={formInput.name}
       }
      />
 
  <input
    placeholder="Salary?"
    onChange={(e) =>
      updateFormInput({ ...formInput, job: e.target.value })
      value={formInput.salary}
    }
  />

  <input
    placeholder="Job?"
    onChange={(e) =>
      updateFormInput({ ...formInput, salary: e.target.value })
      value={formInput.job}
    }
  />
Mina
  • 14,386
  • 3
  • 13
  • 26