You're Invited:Meet the Socket Team at BlackHat and DEF CON in Las Vegas, Aug 4-6.RSVP
Socket
Book a DemoInstallSign in
Socket

mobx-loading-store

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mobx-loading-store

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

0.6.1
latest
Source
npmnpm
Version published
Weekly downloads
5
25%
Maintainers
1
Weekly downloads
 
Created
Source

mobx-loading-store

Build Coverage Status

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:

  • requested — at least one request done, no matter whether it was successful or ended with error;
  • loading — request is executing;
  • loaded — latest request was successful (shorthand for requested && !loading && !error);
  • `loadedOnce' — request was successful at least once;
  • error — latest request is ended with error;
  • errorOnce — request is ended with error at least once.

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

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

Each request status flag can be retrieved separately:

const requested = userStore.requested('load');
const loading = userStore.loading('load');
const loaded = userStore.loaded('load');
const loadedOnce = userStore.loadedOnce('load');
const error = userStore.error('load');
const errorOnce = userStore.errorOnce('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 anyRequested, anyLoading, anyLoaded, anyLoadedOnce, anyError and anyErrorOnce.

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 anyOfRequested(), anyOfLoading(), anyOfLoaded(), anyOfLoadedOnce(), anyOfError(), and anyOfErrorOnce().

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

Keywords

mobx

FAQs

Package last updated on 25 Apr 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts