DEV Community

Amiltonxavier
Amiltonxavier

Posted on

Error when I delete a user: Unhandled Rejection (TypeError): Cannot read property 'error' of undefined

Estou tentando excluir um usuário dentro do meu aplicativo, quando clico no botão que chama a função de exclusão, estou entendendo errado, Rejeição não tratada (TypeError): Não é possível ler a propriedade 'erro' de indefinido. mas quando eu atualizo a página, o usuário é excluído.

export const deleteUser = (clientId, userId, token) => {
    return fetch(`${API}/user/${clientId}/${userId}`, {
        method: 'DELETE',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            Authorization: `Bearer ${token}`
        }
    })
        .then(response => {
            return response.json();
        })
        .catch(err => console.log(err));
};

const destroy = clientId => {
        deleteUser(clientId, user._id, token).then(data => {
            if(data.error) {
                console.error(data.error);
            }else{
                loadUser();
            }
        })
    }

<button onClick={()=> destroy(person._id)} className="btn btn-danger btn-sm">Deletar</button> 

//Node backend

exports.remove = (req, res) =>{
    User
    .findByIdAndRemove(req.params.clientId)
    .exec()
    .then(doc => {
        if(!doc) { return res.status(404).end();}
        return res.status(204).end();
    }) 
    .catch(err => next(err));
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
hnicolas profile image
Nicolas Hervé

In the deleteUser function, if fetch() or response.json() throw an error, it is swallowed by the catch clause. In this case data value in the then clause of the destroy function is undefined and you can't call data.error.

Collapse
 
hnicolas profile image
Nicolas Hervé

I think your problem is that your api call returns an empty body and response.json() fails on responses with an empty body.