Site icon Hip-Hop Website Design and Development

how to update current logged user username

I need to keep in sync the username and the email of my users. I don’t know if there is a better way so I have tried running this code right after the user updates his profile data:

global $wpdb;
$wpdb->update(
    $wpdb->users,
    array('user_login' => $email),
    array('ID' => $user->ID)
);

but this way the auth cookie becomes invalid and the user is logged out.

I have also tried forcing the creation of the auth cookie right after the update, like this:

wp_clear_auth_cookie();
$user = get_user_by( 'id', $user_id ); 
if( $user ) {
    wp_set_current_user( $user_id, $user->user_login );
    wp_set_auth_cookie( $user_id, true );
    do_action( 'wp_login', $user->user_login );
}

but with no results.