TypeError: Cannot assign to read only property 'item' of object '#<Object>'

Viewed 267

I'm having this issue for a days, here is my current state structure:

const [inputFields, setInputFields] = useState([
    {
      item: '',
      quantityIssued: 0,
      quantityRequested: '',
      remarks: '',
      unit: '',
    },
  ])

When I click the edit button I need to fill the date to my state eg.

const editHandler = (order) => {
    const custom = [
      {
        item: 'test',
        quantityIssued: 0,
        quantityRequested: 7,
        remarks: '8',
        unit: '1',
      },
      {
        item: 'test2',
        quantityIssued: 0,
        quantityRequested: 7,
        remarks: '8',
        unit: '1',
      },
    ]
    setInputFields(custom)
  }

When I use that custom data I am able to edit the data of my state but when I try to fetch that data from my server which is the same structure I'll get an error eg:

 const editHandler = (order) => {
    setInputFields(order.orderItems)
  }

although they are the same data which I showed you above, I can't edit if I edit it says that error title can not assign read-only property

this is my interface: enter image description here

1 Answers

Alhamdulillah! finally found the solution after days from this answer: https://stackoverflow.com/a/60960285/12463240

In the handleInputChange I have to do like this:

const handleInputChange = (e, index) => {
    const { name, value } = e.target
    const old = inputFields[index]
    const updated = { ...old, [name]: value }
    var list = [...inputFields]
    list[index] = updated
    setInputFields(list)
  }

Before It was like this:

  const handleInputChange = (e, index) => {
    const { name, value } = e.target
    var list = [...inputFields]
    list[index][name] = value
    setInputFields(list)
  }
Related