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
deleteUser
function, iffetch()
orresponse.json()
throw an error, it is swallowed by thecatch
clause. In this casedata
value in thethen
clause of thedestroy
function isundefined
and 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.