I have two local states, UserList and ModifiedUsers in my App function. The UserList is supposed to capture an array of user objects from an API, and ModifiedUsers will operate on a copy of the array of objects to reverse/sort the list.
const APIURL = "https://jsonplaceholder.typicode.com/users";
function App() {
const [UserList, setUserList] = useState([]);
let [ModifiedUsers, setModifiedUsers] = useState([]);
This getUsers method is used for fetching data from the API and storing it in a local variable users. Which I am then passing to both the UserList array and ModifiedUsers array.
const getUsers = async () => {
let response = await fetch(APIURL);
let users = await response.json();
let modifiedUsers = users;
setUserList(users);
setModifiedUsers(modifiedUsers);
};
This sortList method is called on a button click to sort the array. Even though in this method I am only updating the ModifiedUsers array, it is somehow updating the UserList array as well.
const sortList = () => {
let temp = 0;
for (let i = 0; i < ModifiedUsers.length - 1; i++) {
if (
ModifiedUsers[i].name.trim().length >
ModifiedUsers[i + 1].name.trim().length
) {
temp = ModifiedUsers[i];
ModifiedUsers[i] = ModifiedUsers[i + 1];
ModifiedUsers[i + 1] = temp;
}
}
setModifiedUsers(ModifiedUsers);
if (click % 2 === 0) {
ModifiedUsers.reverse();
setModifiedUsers(ModifiedUsers);
}
setClick(++click);
};
When I console log the UserList Array, I see that it has captured the modified values of ModifiedUsers array, even though I am nowhere updating the original UserList Array.
I am unable to retain the original array of objects no matter what I try. Please help.
Here is the code live on a codepen- https://codesandbox.io/s/api-forked-ie57j4?file=/src/App.js
I have tried creating multiple states, but all of them get updated similarly. I was expecting only the ModifedUsers array to get updated, but all of them did.