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));
}
Top comments (2)
In the
deleteUserfunction, iffetch()orresponse.json()throw an error, it is swallowed by thecatchclause. In this casedatavalue in thethenclause of thedestroyfunction isundefinedand you can't calldata.error.I think your problem is that your api call returns an empty body and response.json() fails on responses with an empty body.