1

today I had some problems with my code.. the thing is I have to create a multiple POST request to the API to pass users to a group, so.. the API request is:

POST /users/user-group-membership

{
  "userId": "string",
  "groupId": 0,
  "isActive": true,
}

Basically i have to grab from the users table the userId from each user and for each userId create a multiple request... so what i did was:

const moveTogroup = async (
  token: string,
  userId: string,
  groupId: number,
): Promise<any> => {
  const res = await axios({
    method: 'POST',
    url: `${API}/users/user-group-membership`,
    data: { userId: userId, groupId: groupId },
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });
  const { data } = res;
  return data;
};

export const moveAllGroup = (
  token: string,
): ThunkAction<void, State, null, UsersActions> => {
  return async (dispatch, getState) => {
    const { userId, groupId } = getState().FleetUsers;
    const convert = userId.toString();
    console.log(convert);
    dispatch(moveUserToGroupRequest());
    try {
      const userPromises = userId.map(() =>
        moveTogroup(token, convert, groupId),
      );
      const move = await Promise.all(userPromises);
      console.log('moving:', move);
      dispatch(moveUserToGroupSuccess(move));
      Swal.fire('Saved', 'Your Changes has been saved', 'success');
    } catch (error) {
      dispatch(moveUserToGroupFailure(error));
      Swal.fire('Error', error, 'error');
    }
  };
};

But as you see this only works for one userId, I grabbing from the state the userId and the groupId, converting the userId to string, and voila is working perfectly, only what I want is depending how much userId I have in the state replied to the request for creating multiple requests and when the user selects in table 2 or 3 users, he or she can move them easily.

2
  • I don't really understand how you retrieve userIds, does getState().FleetUsers contains all users as it suggest? however result is stored in userId suggesting a single user Commented Jan 26, 2021 at 11:06
  • @JeanBouvattier yes, getState().FleetUsers contains all users Commented Jan 26, 2021 at 11:17

1 Answer 1

1

If your userId var contains all userIds, you must map it to recover specific information about each userId :

userId.map((elt) => {
    const convert = elt.toString();
    moveTogroup(token, convert, groupId),
});

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.