0

I have a form that looks like,

const virtual_form = {
    name: 'virtual',
    address_info: [
        {
            name: 'a',
            address: '',
        }
    ]
}

I use this as a default state of my hook

const [virtualForm, setVirtualForm] = useState(virtual_form)

I just providing the user to modify the address field.

<div className="input-text-wrapper">
    <TextField
        value={virtualForm.address_info.address}
        name="address"
        onChange={(e) => handleAccessInfoChange(e, 'virtual')} />
</div>

like above.

However, in my handleAccessInfoChange,

const handleAccessInfoChange = (e, type) => {
    console.log(e.target.name, e.target.value, type)
    switch (type) {
        case 'virtual':
            setVirtualForm({...virtualForm, address_info[0]: [...virtualForm.address_info, address: value] })
    }
}

I am getting a syntax error when I try to change the virtualForm. It says 'address' is not defined no-undef.

How can I make this to only affect the address correctly?

2
  • Is there a reason you have the object with name and address in an array? The array seems unnecessary Commented Jan 24, 2020 at 20:45
  • Because the users should be able to put multiple address_infos in the future Commented Jan 24, 2020 at 20:47

1 Answer 1

2

You're treating the object with address and name as an array, but you cant assign an array with this syntax [address: value]. Its looking for a variable called address not using it as a key.

Instead, map over it and modify the object at the correct index. I have no way to know which index, so I'll assume 0 as in the question:

setVirtualForm({
  ...virtualForm, 
  address_info: virtualForm.address_info.map((info, i) => {
    if (i == 0) {
      return {
        ...info,
        address: value
      }
    }
    return info
  }
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.