Skip to main content

User

As all interactive applications has a user, one or more, Mongez provides a simple interface to handle user data.

Defining current user#

By default the user won't be booted unless is defined explicitly, let's make a simple user.

In src/shared create a user directory with index.ts file, then add in the Module alias section new alias called user, it will look like:

package.json
"_moduleAliases": {    "assets": "src/shared/assets",    "shared": "src/shared",    "apps": "src/apps",    "user": "src/shared/user",    "app": "src/apps/front-office"},

Now run yarn postinstall to generate the new alias.

Let's head to our /src/shared/user/index.ts file.

src/shared/user/index.ts
import { User, setCurrentUser } from 'mongez/user';
// Create basic user const curentUser: User = new User();
setCurrentUser(currentUser); // very important step for other modules to get the current user object
// now let's export the current user object as the default export
export default currentUser;

From now on, we can use the user object directly, like this:

import user from 'user'; // which is alias to src/shared/user
user.get('name'); // Hasan

Login User#

Let's see a simple login way

import user from 'user';
// login the useruser.login({    name: 'Hasan',    email: 'hassaonzohdy@gmail.com',    accessToken: 'ASDFHY5432ASDQWSDEFR432WQSDCGTR54REWSDFGTREWSFGER432WQSDFGHJKIU7654REWDSCVBGHQWSADFHY0', // please note this is very important to be added when calling the login method});

Usually the login method is called after the login form submission, or when creating a user.

The user data will be stored in the current cache driver;

LoginForm.tsx
import user from 'user';// some login serviceimport { login } from './../servies/auth';import { Form, PasswordInput, EmailInput, SubmitButton } from 'mongez/from';
export default function LoginPage() {    const submitLogin = e => {        login(e.target).then(response => {                    user.login(response.data.user); // now the user data is stored in the storage driver        });    };
    return (        <>            <Form onSubmit={submitLogin}>                <EmailInput name="email" placeholder="Email Address" label="Email Address" required />                <PasswordInput minLength={8} name="password" placeholder="Password" label="Password" required />                <SubmitButton>Login</SubmitButton>            </Form>        </>    )}

Check if user is logged in#

Determine whether the user is currently logged in.

import user from 'user';
if (user.isLoggedIn()) {    // do something} else {    // do other things}

Logout#

Now let's remove the user's data from our current storage driver

Header.tsx
import user from 'user';// some logout serviceimport { logout } from './../servies/auth';
import { navigateTo } from 'mongez/router';
export default function header() {    const performLogout = e => {        // clear user's data        user.logout();
        // send API request to clear the user's data        logout();
        // navigate to home page or whatever page you want        navigateTo('/');    };
    return (        <>            <buton onClick={performLogout}>Logout</button>        </>    )}

The user.logout method will clear the user's data from the storage driver and clear the current user's data in the runtime.

Update entire user data#

We can use the update method to update the entire user's data, this can be used in user's profile update response for instance.

import user from 'user';
// some dummy data for demo purposes.user.update({    name: {        first: 'Hasan',    },    address: {        street: {            number: 10,            name: 'My Street'        }    }});
tip

If the passed object to the update method does not have the accessToken key, then the current access token will remain the same, if passed then it will be overrriden.

Updating single value#

As we may need to update only a single value, we can use set instead of update


import user from 'user';
user.set('name', 'Mohammad');

Getting value from user data#

If we need to get a value from current user's data, get method will be handy.

import user from 'user';
// get some value based on the given key
user.get('name'); // for example: Hasan

If the given key does not exist, null will be returned.

import user from 'user';
user.get('role'); // null

If the given key does not exist, we can set a default value to be returned instead of null.

import user from 'user';
user.get('role', 'root'); // root

The get method works wih dot notation syntax to get a value from nested object.

import user from 'user';
user.update({    name: {        first: 'Hasan',    },    address: {        street: {            number: 10,            name: 'My Street'        }    }});
user.get('name.first'); // Hasanuser.get('name'); // returns the entire object: {first: Hasan}user.get('address.street.name'); // My Street

Listen for key change#

When a key's value is changed, we can detect that change using by listening to theat key

import user from 'user';
user.onChange('name', (newValue, oldValue) => {    console.log(oldValue); // Hasan    console.log(newValue); // Mohammad});
// now let's update our data
user.set('name', 'Mohammad'); // once this method is called, the callback will be triggerd
tip

Be aware that the order matters, the onChange method must be defined earlier before updating any data or it won't work as expected.

Getting all user's data#

To retreive the entire object of the current user, all method can be used.

import user from 'user';
user.all(); // the entire object of current user's data