1

I'm trying to change the status in the users array. I'm trying to update the status to 'Yes'. How can i be able to access its data without mutating the state?

Pls see this codesandbox link

CLICK HERE

const dispatch = useDispatch();
  const isLoading = useSelector(state => state.user.isLoading);
  const users = useSelector(state => state.user.users);

  const onApprove = user => {
    dispatch(approveUser(user));
  };

  useEffect(() => {
    dispatch(getUsers());
  }, [dispatch]);

2 Answers 2

1

to change the state in the reducer without mutating try this:

    case 'YOUR_ACTION':
        return {
            ...state,
            users: state.users.map((user) =>
                user.id === action.userId
                    ? {
                          ...user,
                          status: 'yes', // or you could action.status
                      }
                    : user,
            ),
        }

I'm mapping over all users, then matching the user.id with the one sent through from the action and changing the status of it to yes. if it doesn't match, we simply return user

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Red Baron
1

Update the approveUser action to take and pass the user

export function approveUser(user) { // <-- receive user object
  return dispatch => {
    dispatch({
      type: userConstants.APPROVE_USER_REQUEST
    });
    dispatch({
      type: userConstants.APPROVE_USER_SUCCESS,
      payload: {
        approved: "HAHAHHA"
      },
      user, // <-- pass user object
    });
    dispatch({
      type: userConstants.APPROVE_USER_FAILURE,
      payload: {}
    });
  };
}

Then update the reducer to spread update in. Use the received user object to map the new 'yes' status.

case userConstants.APPROVE_USER_SUCCESS:
  return {
    ...state,
    isLoading: false,
    users: state.users.map(user => user.id === action.user.id ? {
      ...user,
      status: 'yes',
    } : user)
  };

Edit Update State Redux

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.