useUser()

The useUser() composable allows for:

  • signing a user in
  • signing a user out
  • registering a new user
  • loading a user
  • updating a user's profile
  • changing a user's password

user

Main data object populated by the load() method.

Type

const user: ComputedProperty<User>

References: User

loading

Indicates whether any of the composable methods is in progress.

Type

const loading: ComputedProperty<boolean>;

error

Contains errors thrown by any of the composable methods.

Type

const error: ComputedRef<UseUserError>;

References: UseUserError

isAuthenticated

Indicates whether a user session is anonymous or authenticated.

Type

const isAuthenticated: ComputedRef<boolean>;

load()

Fetches a user from the API and populates the user property. Under the hood, it sends a request to the getUser API endpoint.

Type

type LoadUserProps = BaseProps

async function load: (props?: LoadUserProps) => Promise<void>

References: LoadUserProps, BaseProps

Example

In the following example, we are loading a user and exposing the populated user property to the templates by returning it from the setup() function. We are also providing the fields parameter to specify a subset of fields to be returned in the response.

import { onMounted } from '@nuxtjs/composition-api';
import { useUser } from '@vsf-enterprise/sapcc';

export default {
  setup() {
    const { user, load: loadUser } = useUser();

    onMounted(async () => {
      await loadUser({ fields: 'name,title,uid' });
    });

    return { user };
  }
};

login()

Initializes an authenticated user session by retrieving an access token and populating the user property. Under the hood, it sends two requests: one to the OAuthUserAuthorization API endpoint (to retrieve the access token) and one to the getUser API endpoint (to retrieve the logged-in user profile).

The retrieved access token is stored as vsf-sap-token cookie.

Type

interface LoginUserProps extends BaseProps {
  username: string;
  password: string;
  isRememberMe?: boolean;
}

async function login: (props: LoginUserProps) => Promise<void>

References: LoginUserProps, BaseProps

Example

In the following example, we are creating a simple wrapper for the login() method. It accepts username and password as parameters and passes them on with the login() method call.

import { useUser } from '@vsf-enterprise/sapcc';

export default {
  setup() {
    const { login } = useUser();

    const loginUser = async (username, password) => {
      await login({ username, password });
    };

    return { loginUser };
  }
};

logout()

Terminates an authenticated user session by removing the vsf-sap-token cookie and setting the user property to null.

Type

async function logout: () => Promise<void>

Example

import { useUser } from '@vsf-enterprise/sapcc';

export default {
  setup() {
    const { logout } = useUser();

    const logoutUser = async () => {
      await logout();
    };

    return { logoutUser };
  }
};

register()

Creates a new user. Under the hood, it sends a request to the createUser API endpoint. It does not sign the new user in automatically and does not alter the user property.

Immediate login

If you want users to be automatically signed-in upon registration (without an additional verification step such as an email confirmation), call the login() method right after calling register().

Type

interface RegisterUserProps {
  firstName: string;
  lastName: string;
  password: string;
  uid: string;
  titleCode?: string;
}

async function register: (props: RegisterUserProps) => Promise<void>

References: RegisterUserProps

Example

In the following example, we are creating a simple wrapper around the register() method. It creates a new customer in the SAP Commerce Cloud database and calls login() immediately after a successful registration.

import { useUser } from '@vsf-enterprise/sapcc';

export default {
  setup() {
    const { register, login } = useUser();

    const registerAndLogin = async () => {
      const params = {
        firstName: 'John',
        lastName: 'Doe',
        password: 'Securepassword1!',
        uid: 'johndoe@gmail.com'
      };

      await register(params);
      await login({ username: params.uid, password: params.password });
    };

    return { registerAndLogin };
  }
};

Good to know!

In SAP Commerce Cloud, every password needs to contain at least one uppercase character, a number and a special character.

update()

Updates an existing user profile and saves it to the user property. Under the hood, it sends a request to the updateUser API endpoint.

Good to know

The updateUser API method sends a PATCH request to the SAP's Update User Endpoint (opens new window). As a result, only attributes provided in the request body are changed.

Type

interface UpdateUserProps extends BaseProps {
  user: User;
}

async function update: (props: UpdateUserProps) => Promise<void>

References: UpdateUserProps, BaseProps, User

Example

In the following example, we are creating a simple wrapper around the update() method. It changes the firstName and the lastName of an existing user. It also specifies a subset of fields to be returned with the response and saved to the user property.

import { useUser } from '@vsf-enterprise/sapcc';

export default {
  setup() {
    const { update } = useUser();

    const updateUser = async (firstName, lastName) => {
      await update({
        user: { firstName, lastName },
        fields: 'firstName,lastName'
      });
    };

    return { updateUser };
  }
};

changePassword()

Updates an existing user password. Under the hood, it sends a request to the changePassword API endpoint. It does not alter the user property.

Type

interface ChangeUserPasswordProps {
  new: string;
  old: string;
}

async function changePassword: (props: ChangeUserPasswordProps) => Promise<void>

References: ChangeUserPasswordProps

Example

import { useUser } from '@vsf-enterprise/sapcc';

export default {
  setup() {
    const { changePassword } = useUser();

    const changeUserPassword = async (oldPassword, newPassword) => {
      await changePassword({
        old: oldPassword,
        new: newPassword
      });
    };

    return { changeUserPassword };
  }
};

set()

Sets the user property manually. Useful in scenarios where an explicit API method call is required (e.g. loading a user with getUser API method). It does not perform any async call under the hood and its progress is not indicated by the loading property.

Type

function set: (newUser: User | null) => void;

References: User

Example

In this example, we are bypassing the load() method and using the getUser API endpoint directly to fetch a user profile. Then, we're leveraging the set() method to populate the user property.

import { onMounted } from '@nuxtjs/composition-api';
import { useUser } from '@vsf-enterprise/sapcc';
import { useVSFContext } from '@vue-storefront/core';

export default {
  setup() {
    const { $sapcc } = useVSFContext();
    const { set: setUser } = useUser();

    onMounted(async () => {
      const user = await $sapcc.api.getUser();
      setUser(user);
    });
  }
};