Answer the question
In order to leave comments, you need to log in
How to make the component track changes in the state in the array?
I have different components. In one, the array is sorted in the state. And the second does not react to these changes. I understand that he needs to somehow follow this, but I can’t figure out how to write it.
1st Component (does sorting)
const onChangeSelectHandler = (e) => {
let select = e.target.value;
if (select === "az") {
const newUsers = users.sort();
dispatch(setSortUsers(newUsers));
}
if (select === "za") {
const newUsers = users.sort().reverse();
dispatch(setSortUsers(newUsers));
}
};
<select onChange={onChangeSelectHandler}>
export const setSortUsers = (users) => ({
type: SET_SORT_USERS,
payload: users,
});
const initialState = {
users: [],
};
case SET_SORT_USERS:
return {
...state,
users: action.payload,
};
const Content = () => {
const name = useSelector(({ users }) => users.searchName);
const users = useSelector(({ users }) => users.users);
return (
<ul>
{name
? <div>{name}</div>
: users.map((user) => <li key={user}>{user}</li>)
}
</ul>
);
};
useEffect(() => {
dispatch(fetchUsers());
}, []);
Answer the question
In order to leave comments, you need to log in
users.sort() and users.sort().reverse() do not create a new array, but change the current one.
const newUsers = users.slice().sort();
const newUsers = users.slice().sort().reverse();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question