Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I fill in frontend the ID for deleting a user?

I can’t delete the one which I select on the page. It deletes every time the first one on the list.

I don’t know if it has anything to do with the backend. If that’s the case you have to tell me, then I would take it in with me in the backend.

My UserManagement.js:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function UserManagement({ history }) {
 
  const dispatch = useDispatch();
  
  const userLogin = useSelector((state) => state.userLogin);
  const userList = useSelector((state) => state.userList);
  const { loading  } = userLogin;
  const { users} = userList;

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

  const deleteHandler = (id) => {
    if (window.confirm("Are you sure? you want to delete")) {
      dispatch(deleteUserAction(id));
    }
  };

  
  console.log(userList);
  console.log(users);
  return (
    <MainScreen title={`List of Users`}>
       <Link to="/createUser" id="OpenCreateUserDialogButton">
        <Button style={{ marginLeft: 10, marginBottom: 6 }} size="lg">
          Create new User
        </Button>
      </Link>
      
      {loading && <Loading />}
     
      {users &&
        users?.map((users) => (
         
          <Accordion>
            <Card style={{ margin: 10 }} key={users._id}>
              <Card.Header style={{ display: "flex" }}>
                <span
                  // onClick={() => ModelShow(note)}
                  style={{
                    color: "black",
                    textDecoration: "none",
                    flex: 1,
                    cursor: "pointer",
                    alignSelf: "center",
                    fontSize: 18,
                  }}
                >
                      
                      {users.userID}               
                </span>
                <div>
                  <Link to="/profileedit">
                    <Button
                    id="EditButton"
                    >Edit</Button>
                    </Link>
                    <Button
                      id="DeleteButton"
                      variant="danger"
                      className="mx-2"
                      onClick={() => deleteHandler(users.id)}
                    >
                      Delete
                    </Button>
                  </div>
              </Card.Header>

And this is my userAction:

  export const deleteUserAction = (_id) => async (dispatch, getState) => {
    try {
      dispatch({
        type: USER_DELETE_REQUEST,
      });
  
      const {
        userLogin: { userInfo },
      } = getState();
  
      const url = "http://localhost:8080/user/:id";
  
      const config = {
        headers: {
          Authorization: `Bearer ${userInfo.token.token}`,
        },
      };
      console.log(userInfo.token.token);
      const { data } = await axios.delete(url, config);
  
      dispatch({
        type: USER_DELETE_SUCCESS,
        payload: data,
      });
    } catch (error) {
      const message =
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message;
      dispatch({
        type: USER_DELETE_FAIL,
        payload: message,
      });
    }
  };

The backend:


exports.deleteUser = async (request, response) => {
  try{
      await User.findByIdAndDelete({_id: request.params.id});
      response.status(201).json("User deleted Successfully");
  } catch (error){
      response.status(409).json({ message: error.message});     
  }
}

The error which been showed by Chrome network

{"message":"Cast to ObjectId failed for value "{ _id: ‘:id’ }" (type Object) at path "_id" for model "user""

>Solution :

On your axios request you are missing the id when setting up the url, since your backend picks up the id by the request params.

This

const url = "http://localhost:8080/user/:id";

Should be this

const url = `http://localhost:8080/user/${_id}`;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading