-2

I have a read-only object that is returned by GraphQL (vue-apollo) query, the result which is read-only looks something like this:

result: {
  id: 'yh383hjjf',
  regulations: [{ title: 'Test', approved: false}]
})

I want to bind this to a form and be able to edit/update the values in the regulations array and save it back to the database.

at the moment when I try to edit I get the error below:

Uncaught TypeError: "title" is read-only

I tried cloning the result returned by the database using object.assign

//target template
const regulatoryApprovals = {
  id: null,
  regulations: [{ title: null, approved: null}]
})

regulatoryApprovals = Object.assign(regulatoryApprovals, result, {
  regulations: Object.assign(regulatoryApprovals.regulations, result.regulations)
})

but this didn't work.

Does anyone know how I can properly clone the result?

capiono
  • 2,875
  • 10
  • 40
  • 76
  • Please, specify what is your intention regarding `regulations`. What exactly `result` is and what exactly you expect as the output. – Estus Flask Apr 25 '21 at 13:25
  • Thanks. It's still unclear how regulatoryApprovals.regulations and result.regulations should be merged. – Estus Flask Apr 25 '21 at 13:44
  • I created regulatoryApprovals as a template for cloning the result object returned from the database. Not sure if that is even needed. sorry for the confusion. – capiono Apr 25 '21 at 13:59
  • It's likely not needed then. What are the roles of `id: null` and `[{ title: null, approved: null}]`? `result` already contains these fields. Basically `Object.assign` does a merge, not a clone. The error occurs because you merge to readonly `regulations`. array. In order to clone, you need to merge to empty object. – Estus Flask Apr 25 '21 at 14:09

1 Answers1

0

regulatoryApprovals= Object.assign(regulatoryApprovals, ... indicates the problem because regulatoryApprovals is modified with Object.assign, so it would need no assignment.

Read-only regulatoryApprovals object needs to be cloned. regulations is an array and won't be merged correctly with Object.assign, unless it's known that array elements need to be replaced. It should be:

regulatoryApprovals = {
  ...regulatoryApprovals,
  ...result,
  regulations: [...regulatoryApprovals.regulations, result.regulations]
}

Where { ...regulatoryApprovals, ... } is a shortcut for Object.assign({}, regulatoryApprovals, ...).

Estus Flask
  • 206,104
  • 70
  • 425
  • 565