lunex
TypeScript icon, indicating that this package has built-in type declarations

1.0.4 • Public • Published

Lunex

Lunex is a lightweight, framework agnostic, typescript friendly, state management library inspired by Vuex/Pinia.

Installation

yarn add lunex
npm install lunex

Getting Started

Create a store:

// authStore.ts
import { createStore } from 'lunex';
import { api } from '~/api';

type User = {
  name: string;
};

type StoreState = {
  user?: User;
};

type StoreGetters = {
  isLoggedIn: boolean;
};

type StoreActions = {
  login: (payload: User) => Promise<void>;
  logout: () => Promise<void>;
};

export const authStore = createStore<StoreState, StoreGetters, StoreActions>({
  state: {},
  actions: {
    login: async (
      state: StoreState,
      payload: { username: string; password: string },
    ) => {
      const user = await api.login(username, password);
      return { user };
    },
    logout: async (state: StoreState) => {
      await api.logout();
      return {};
    },
  },
  getters: {
    isLoggedIn: (state: StoreState): boolean => !!state.user,
  },
  plugins: [
    (state: StoreState) => console.debug('PLUGIN: ', JSON.stringify(state)),
  ],
});

then use the store:

import { authStore } from '~/stores/authStore';

console.log(JSON.stringify(authStore.state));

// {}

const unsubscribeFromState = authStore.state$.subscribe((state) =>
  console.log(`SUBSCRIPTION(state$):  ${JSON.stringify(state)}`),
);

// SUBSCRIPTION(state$): {}

console.log(JSON.stringify(authStore.isLoggedIn));

// false

const unsubscribeFromIsLoggedIn = authStore.isLoggedIn$.subscribe(
  (isLoggedIn) =>
    console.log(
      `SUBSCRIPTION(isLoggedIn$): user is ${isLoggedIn ? '' : 'not'} logged in`,
    ),
);

// SUBSCRIPTION(isLoggedIn$): user is not logged in

authStore.login({ username: 'user-1', password: 'pass123' });

// PLUGIN: { user: { name: 'curtis' } }

// SUBSCRIPTION(state$):  { user: { name: 'curtis' } }

// SUBSCRIPTION(isLoggedIn$): user is logged in

console.log(JSON.stringify(authStore.state));

// { user: { name: 'curtis' } }

console.log(JSON.stringify(authStore.isLoggedIn));

// true

authStore.logout();

// PLUGIN: {}

// SUBSCRIPTION(state$):  {}

// SUBSCRIPTION(isLoggedIn$): user is not logged in

unsubscribeFromState();

unsubscribeFromIsLoggedIn();

Package Sidebar

Install

npm i lunex

Weekly Downloads

1

Version

1.0.4

License

MIT

Unpacked Size

6.48 kB

Total Files

6

Last publish

Collaborators

  • curtishughes