0.4.0 • Published 5 months ago

mobx-loading-store v0.4.0

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

mobx-loading-store

npm.io Build Coverage Status npm.io

Abstract class for MobX store to control API requests' state out-of-the-box.

Installation

pnpm install mobx-loading-store -P

Usage

Extend your store from LoadingStore and use request() or requestUndefined() methods to make your API requests. It will allow you to control requests' statuses such as loading, error, requested and loaded.

The difference between request() and requestUndefined() is the former throws LoadingStoreError on request error, the latter returns undefined. In order to handle errors the former is more suitable.

export type UserRequestType = 'load' | 'save';

export class UserStore extends LoadingStore<UserRequestType> {
  @observable user?: User;
  
  @action async load(id: number): Promise<User> {
    return this.request('load', async () => {
      const response = await api.user.load(id);
      return responseToUser(response);
    }, {
      onSuccess: (user) => {
        this.user = user;
      }
    });
  }
} 

In component (React is an example):

import { observer } from 'mobx-react-lite';
import { useEffect, useState } from 'react';
import { LoadingStoreError } from './loading.store';

import { UserStore } from './user.store';

export const UserName = observer(() => {
  const [userStore] = useState(() => new UserStore());
  const { user } = userStore;

  useEffect(() => {
    userStore.load().catch((e) => {
      if (e instanceof LoadingStoreError) {
        if (e.error.code === 401) {
          alert('User is not authorized');
          return;
        }
      }
     alert('Unable to load user data');
    });
  }, []);

  return <div>{user?.name}</div>;
}); 

Request status

Each request's status is an @observable object of RequestStatus type consisting of the following boolean flags:

  • loading — request is executing;
  • error — request is added with error;
  • requested — at least one request done, no matter whether it was successful or failed;
  • loaded — latest request is successful (shorthand for requested && !loading && !error);

Request status can be retrieved at once by calling requestStatus():

const requestStatus = userStore.requestStatus('load');
const { loading, error, requested, loaded } = requestStatus;

Each request status flag can be retrieved separately:

const loading = userStore.loading('load');
const error = userStore.error('load');
const requested = userStore.requested('load');
const loaded = userStore.loaded('load');

If store can execute few requests of different types the following can be used to detect whether at least one request has corresponding status flag set to true:

const requestStatus = userStore.requestAnyStatus;

Corresponding separate properties are anyLoading, anyError, anyRequested and anyLoaded.

If you want to get the same request status combing only specific requests then requestAnyOfStatus() can be used:

const requestStatus = userStore.requestAnyOfStatus(['load', 'save']);

Corresponding separate methods are anyOfLoading(), anyOfError(), anyOfRequested() and anyOfLoaded().

If the latest request is ended with error (error === true) one can get error code and error instance:

const error = userStore.error('load');
if (error) {
  const errorCode = userStore.errorCode('error');
  const errorInstance = userStore.errorInstance('error');
}

IMPORTANT!

In order to get error code and error instance requestErrorExtractor function must be passed to LoadingStore constructor. By default handling axios errors only is supported at the moment.

Build

pnpm build

Develop

pnpm dev

Test

pnpm lint
pnpm test
pnpm test:coverage

Changelog

Changelog is available here.

License

MIT

0.4.0

5 months ago

0.3.0

5 months ago

0.2.0

5 months ago

0.1.0

5 months ago