# 7.3: Persisting Profile Changes

Now, instead of console.logging our changes, let's implement persisting our changes back to the database.

## Adding UserForUpdate DTO

We need to create a new data transfer object to represent the data we are sending from our update form to the server.

In your .Models project, add a new class called UserForUpdate.cs inside of the User folder.

```csharp
public class UserForUpdate
{
    public string Introduction { get; set; }
    public string LookingFor { get; set; }
    public string Interests { get; set; }
    public string City { get; set; }
    public string State { get; set; }
}
```

## Add Method to the UserService

Add a method signature in the IUserService.cs class:

```csharp
Task<bool> UpdateUser(int id, UserForUpdate userForUpdate);
```

In the `UserService` class, implement the new method:

```csharp
public async Task<bool> UpdateUser(int id, UserForUpdate model)
{
    var user = await _context.Users
                        .FirstOrDefaultAsync(u => u.Id == id);

    user.Introduction = model.Introduction;
    user.LookingFor = model.LookingFor;
    user.Interests = model.Interests;
    user.City = model.City;
    user.State = model.State;

    return await _context.SaveChangesAsync() == 1;
}
```

## Add UpdateUser() method and endpoint to the UsersController

In the `UsersController.cs` file, add a new HttpPut method for UpdateUser():

```csharp
[HttpPut("{id}")]
public async Task<IActionResult> UpdateUser(int id, [FromBody]UserForUpdate userForUpdate)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    var currentUserId = int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);

    var userFromRepo = await _userService.GetUser(id);

    if (userFromRepo == null)
        return NotFound($"User could not be found.");

    if (currentUserId != userFromRepo.Id)
        return Unauthorized();

    if (await _userService.UpdateUser(id, userForUpdate))
        return NoContent();

    throw new Exception($"Updating user failed on save.");
}
```

## Testing

In Postman, send a Put request to /api/users/{id} - entering an appropriate id from your database (in the example I'm using 2103 - yours will likely be different). Don't forget to provide a fresh Bearer token from the user you are updating in the header.

You should get a 204 No Content response:

![UpdateUser](https://122480229-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LAU8YfVcpLNVPaSQtyc%2F-LAU8fPjgm_DRb3Jf3Aw%2F-LAU8vZ4kXv2ylcc6HES%2Fupdateuserpostman.png?generation=1524162354426886\&alt=media)

You can send a get request to the same endpoint to check that it has changed:

![CheckUpdateUserPostman](https://122480229-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LAU8YfVcpLNVPaSQtyc%2F-LAU8fPjgm_DRb3Jf3Aw%2F-LAU8v_zXlOqiNBut7iw%2Fcheckupdateduserpostman.png?generation=1524162348671935\&alt=media)

The changes should also be reflected in the Angular application:

![CheckUpdateUserAngular](https://122480229-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LAU8YfVcpLNVPaSQtyc%2F-LAU8fPjgm_DRb3Jf3Aw%2F-LAU8vbd-QjP5JHJXbR2%2Fcheckupdateduserangular.png?generation=1524162348786885\&alt=media)

We've tested the "happy path", let's test a couple of scenarios when something goes wrong.

First, let's try to update a user that doesn't exist. Send repeat the previous request, but change the id to something you know doesn't exist in your database.

You should get a 404 Not Found response with a body of "User could not be found."

![User404d](https://122480229-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LAU8YfVcpLNVPaSQtyc%2F-LAU8fPjgm_DRb3Jf3Aw%2F-LAU8vcqzbwv5o3kprf6%2Fuser404.png?generation=1524162348663185\&alt=media)

Next, let's try to update a that is different from the one we have a token for. Change the id in the endpoint to another user's id:

You should get a 401 Unauthorized response.

![User401d](https://122480229-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LAU8YfVcpLNVPaSQtyc%2F-LAU8fPjgm_DRb3Jf3Aw%2F-LAU8veLeRyK7vjZhcEk%2Fuser401.png?generation=1524162348654349\&alt=media)

## Persisting Changes Made on the Client

In `user.service.ts`, add an updateUser() method:

```typescript
updateUser(id: number, user: User) {
    return this._http.put(this.baseUrl + 'users/' + id, user);
}
```

In `member-edit.component.ts`, update the updateUser() method to use the UserService instead of console.logging:

```typescript
updateUser() {
    this._userService.updateUser(this._authService.decodedToken.nameid, this.user).subscribe(next => {
        this._alertify.success('Profile updated successfully.');
        this.editForm.reset(this.user);
    }, error => {
        this._alertify.error(error);
    });
}
```

Test it out in the browser. You should be able to update profile fields, save them, and see that the changes have persisted.

![AngularChangesPersisted](https://122480229-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LAU8YfVcpLNVPaSQtyc%2F-LAU8fPjgm_DRb3Jf3Aw%2F-LAU8vnX9_MhgI_5P8E3%2Fangularchangespersisted.png?generation=1524162348733775\&alt=media)
