A
A
arctic072022-02-06 18:19:03
React
arctic07, 2022-02-06 18:19:03

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}>


through redax, this is all sent to the state:
export const setSortUsers = (users) => ({
  type: SET_SORT_USERS,
  payload: users,
});

const initialState = {
  users: [],
};

case SET_SORT_USERS:
  return {
  ...state,
  users: action.payload,
};


and the 2nd component that should change the list after this sorting:
(I also have a search there, but it works) (by name)
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>
  );
};


And an array of names (strings) is loaded into users when the App.js component is loaded:
useEffect(() => {
    dispatch(fetchUsers());
  }, []);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2022-02-06
@Alexandroppolus

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 question

Ask a Question

731 491 924 answers to any question