Search code examples
javascriptreactjsarraysinputpush

How to input multiple values from same input field in react


This is my code

const Diagnosis = () => {

  const medicine =[]
  var [inputs , setInputs] = useState()
  const handleChange = (event) => {
    setInputs(event.target.value)
    
  };
  const handleAdd = () => {
    medicine.push(inputs)
  };
}
return (
    <div className='container'>
    <div>
    <h1 className='heading'>DIAGNOSIS</h1>
      <form>
          <label className='label'>
            Medicine :<br/>
            <input className='input' name='medicine' type='text' placeholder='One medicine at a time' onChange={handleChange}  value={inputs}/>
            </label><br/>
            </form>
          <Button variant="contained" onClick={handleAdd}>Add medicine</Button>
    </div>
    </div>
  )
}

The way it's supposed to work is , user enter value in the input field and onclick that input gets pushed into medicine array But for some reason , once the user changes the input field , the medicine array becomes empty

I can't figure what i am doing wrong in here and is there any better way to store multiple inputted from the same input field in an array

I've tried everything i could think of but in no matter what , whenever there is any change in input field , medicine array becomes empty suddenly


Solution

  • const medicine =[]
    

    This local variable will be re-created every time the component renders, so it's always replaced by an empty array. If you want the array to persist between renders it should be a state:

    const [medicine, setMedicine] = useState([]);
    // ...
    const handleAdd = () => {
      setMedicine(prev => {
        return [...prev, inputs];
      })
    };