close

[Solved] TypeError: Cannot assign to read only property ‘0’ of object ‘[object Array]’

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error TypeError: Cannot assign to read only property ‘0’ of object ‘[object Array]’ in javascript. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How To Solve TypeError: Cannot assign to read only property ‘0’ of object ‘[object Array]’ Error ?

  1. How To Solve TypeError: Cannot assign to read only property '0' of object '[object Array]' Error?

    To Solve TypeError: Cannot assign to read only property '0' of object '[object Array]' Error Try creating a copy of the Array before trying to sort it. Like using a spread operator. arrayForSort = [...this.taskList]. Then after sorting you could assign it back to the taskList field.

  2. TypeError: Cannot assign to read only property '0' of object '[object Array]'

    To Solve TypeError: Cannot assign to read only property '0' of object '[object Array]' Error Try creating a copy of the Array before trying to sort it. Like using a spread operator. arrayForSort = [...this.taskList]. Then after sorting you could assign it back to the taskList field.

Solution 1

Try creating a copy of the Array before trying to sort it. Like using a spread operator.

arrayForSort = [...this.taskList]

Then after sorting you could assign it back to the taskList field

Solution 2

For those coming to this issue with this error message using React/Redux, it might be that you’re trying to mutate state directly which isn’t allowed.

In my case I had this setup for getting state within a thunk (simplified):

import store from "./myStore";

const state = store.getState();
const getItems = state => state.user.items;
const items = getItems(state);
// ↓ this blew up as it was attempting to manipulate `state`
items.sort((a, b) => a.order - b.order);

This was fixed for me by:

import store from "./myStore";

const state = store.getState();
const getItems = state => state.user.items;
// ↓ in my case items is an array, so I create a new array by spreading state here
const items = [...getItems(state)];
// ↓ which means we're not manipulating state, but just our `items` array alone
items.sort((a, b) => a.order - b.order);

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read

Leave a Comment