-1

I am trying to change the value, but I am getting this error " Cannot assign to read-only property 'name' of object '#'?"

Code for reference


interface MyForm
{
    name:string,
    passwor:string,
    [key:string]:any
}


const [student,setStudent] = useState<MyForm>(
    {
        name:'',
        password:''
    }
)

const handleForm = (e:React.ChangeEvent<HTMLInputElement>) =>{
    const key : string = e.target.id
    student[key] = e.target.value
    setStudent({...student})
}

<input id="name" label="enter name" value={student.name}  onchange={handleForm} />
<input id="password" label="enter name" value={student.name}  onchange={handleForm} />


Edit

I solved this issue, I made changes in handleForm



const handleForm = (e:React.ChangeEvent<HTMLInputElement>) =>{
    const {name,value} = e.target
    setStudent({...student,[name]:value})
}



Thank you.

  • check this [answer](https://stackoverflow.com/a/44288357/5566935) – Mohammad Abdul Alim May 21 '21 at 16:18
  • Does this answer your question? [Cannot assign to read only property 'name' of object '\[object Object\]'](https://stackoverflow.com/questions/44288164/cannot-assign-to-read-only-property-name-of-object-object-object) – Mark Schultheiss May 21 '21 at 16:22
  • Nope, I checked that but didnt help – Pranav peddi May 21 '21 at 16:23
  • I would suggest you start with fixing any issues in your code like `passwor:string,` just seems wrong to me here as a starting point. `setStudent` is that not defined? (as an aside, I find the id of `name` to perhaps not be a well-thought out value given a "name" attribute exists in html https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes i.e. your `e.target.name` is the non-existent reference to the name attribute not the id property. So this is really a typo and probably should be closed as such – Mark Schultheiss May 21 '21 at 16:30
  • Please check the edit now. – Pranav peddi May 21 '21 at 16:37

1 Answers1

0

Update your code as:

interface MyForm
{
    name:string,
    password:string
    // [key:string]:any
}

type FormField = keyof MyForm;

function MyComponent(props) {

 const [student,setStudent] = useState<MyForm>(
    {
        name:'',
        password:''
    }
 )

 const handleForm = (e:React.ChangeEvent<HTMLInputElement>) =>{
    const key : FormField = e.target.name; // If it not work then use const key:FormField = e.target.name as any; // Usually we should avoid any
    student[key] = e.target.value
    setStudent({...student})
 }

 return (
   <>
     <!-- Add name attribute here -->
     <input id="name" name="name" label="enter name" value={student.name}  onChange={handleForm} />
     <!-- A Update here -->
     <input id="password" name="password" label="enter name" value={student.password}  onChange={handleForm} />
   </>
 );
}
YATIN GUPTA
  • 916
  • 9
  • 17