This page is a work in progress.You can help improve it. →

Restaurant Delete

Restaurant Delete

When a user views a restaurant they created, we can add a delete button to remove the restaurant.

Update the Restaurant.tsx

We start by adding history (for redirecting)

const history = useHistory()

We also define a handleDelete method to send the API request:

async function handleDelete(event) {
event.preventDefault()
const response = await fetch(`/api/Restaurants/${id}`, {
method: 'DELETE',
headers: { 'content-type': 'application/json', ...authHeader() },
})
if (response.status === 200 || response.status === 204) {
history.push('/')
}
}

and finally, a button that is rendered only if the current user-id matches:

{
restaurant.userId === getUserId() ? (
<button onClick={handleDelete}>Delete</button>
) : null
}

Updating the Restaurants controller

We'll add [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] to the HttpDelete method to ensure authentication.

And since we can't 100% trust that hiding the delete button on the client is enough to prevent unauthorized users, we'll add a check on the server-side.

if (restaurant.UserId != GetCurrentUserId())
{
// Make a custom error response
var response = new
{
status = 401,
errors = new List<string>() { "Not Authorized" }
};
// Return our error with the custom response
return Unauthorized(response);
}
© 2017 - 2022; Built with ♥ in St. Petersburg, Florida.