0

Trying to make a simple CRUD app using react, axios and mongoose.

Here is my axios:

deleteUser(id) {
    axios.delete(`${rootUrl}/api/users/${this.state.id}`, {
        params: { id }
    })
    .then(response => {
        // this.setState({ users: response.data });
        console.log('deleteUser response', response, this.state);
    });
}

Here is the relevant API route:

router.delete('/users/', (req, res) => {
    const { id } = req.body;

    User.findByIdAndDelete(id, (error, data) => {
        if (error) {
            console.log('error in deleting!');
            throw error;
        } else {
            console.log('user has been deleted', data);
            res.status(204).json(data);
        }
    });
});

It returns

DELETE /api/users/?id=5b34e5b5dfef8b4sd234567 204 47.816 ms - -

But when I GET users, the deleted user remains.

Here is the render I am mapping state into. I think I am pulling the id in properly but I am not sure what else to try:

{this.state.users.map(user => {
    return (
        <div className="Users1" key={user._id}>
            <Card>
                <CardBody>
                    <CardTitle>{user.username}</CardTitle>
                    <CardText>{user._id}</CardText>

                    <Button onClick={() => this.deleteUser(user._id)}
                            key={user._id}
                            type="button"
                            color="danger"
                    >
                        X
                    </Button>
                </CardBody>
            </Card>
        </div>       
    );
})}

and here is state:

state = {
    users: [],
    id: ''
};
4
  • can you log req.body? Commented Jun 28, 2018 at 16:06
  • When I log req.body, server-side, it returns an empty object {}
    – Khepf
    Commented Jun 28, 2018 at 16:51
  • Curiously enough, if I use Postman to delete by using the id as an object in the body, then logging req.body does show the id, but it still doesn't get deleted.
    – Khepf
    Commented Jun 28, 2018 at 19:23
  • There's definitely something wrong from the client side. Commented Jun 29, 2018 at 5:38

1 Answer 1

0

I had a similar problem. I had success by looking at the req.query property on the API server, rather than req.body:

const { id } = req.query;

I figured it out by dumping the entire req object to the console.

On the client side, my request did not include the id in the URL. I just included it in the params object. This seemed to help. So the equivalent call in your code would look something like this:

axios.delete(`${rootUrl}/api/users/`, {
    params: { id }
})

I hope this helps. I'm still just learning React Native, so I'm hardly an expert. But I wanted to share what worked for me in case it helps others.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.