I've tried to change this so many ways, no matter how it's done/explained on other Stack Overflow posts. I have an array of objects, and I am trying to map/loop through the array move one of the objects to the front of the array.
Here's what I've got:
const [users, setUsers] = useState<User[]>([]);
const [primaryUser, setPrimaryUser] = useState<User>({
id: 0;
first_name: "",
last_name: ""
})
useEffect(() => {
users.map((user, i) => {
if(user.id === 12345) {
users.splice(i, 1);
users.unshift(user)
setPrimaryUser(user);
}
});
setUsers(users);
}, [])
Whether I map as shown above or use a for loop, I always end up getting the following error: TypeError: Cannot assign to read only property 'x' of object '[object Array]'
Any suggestions/help is greatly appreciated. Thanks in advance!
if(user.id = 12345)this is assignment, not equality. Moreover, you should probably avoid mutatingusersvia.splice()and.unshift(). Also, as a side note, please don't use.mapas a simple iteration. If you're not doing a mapping operation, use.forEachor a simple loop.if(user.id === 12345) {. Also, I've tried aforEachandforloop. Still getting the same error every time.let tempUsers = users, mutating that, setting it -setUsers(tempUsers)and still the same thing.let tempUsers = userswill not make a copy of the array! Copy array by value