menu

Questions & Answers

Update and delete an object within an array of a Pinia store in Vue

I am making a CRUD in Vue 3 and I am using Pinia to save my objects as an array. Everything works fine but already when I want to update one of the objects I get the error of:

[Vue warn] Set operation on key "id" failed: target is readonly

[Vue warn] Set operation on key "length" failed: target is readonly

In my store I define my array as follows:

const companies = ref<Company[]>([])

In my composable since I have the object with the updated data stored in data.data and the id parameter which is an attribute of the object I try to do the following:

const { companies } = store
const index = companies.findIndex(c => c.id = id)
if(index > -1)
     companies.splice(index, 1, data.data)
store.setCompanies(companies)

However, it is in the splice method that gives me this error, whether I want to use it to replace the object or to remove it from the array. I have seen that there is a store.$patch method but I do not know if it applies to this case, and if I wanted to apply a filter and then replace the entire array in the long run that are many objects I don't see it convenient.

Comments:
2023-01-21 23:20:08
What's the purpose of store.setCompanies(companies) ? You either mutate companies directly (which is not a good practice) or do this with an action, not both. Probably the array needs to be copied instead
2023-01-21 23:20:08
you have to call storeToRefs in order to make the companies reactive outside the store. checkL pinia.vuejs.org/core-concepts/index.html#using-the-store
Answers(0) :