0.0.45-alpha • Published 2 years ago

@crux/store v0.0.45-alpha

Weekly downloads
-
License
-
Repository
-
Last release
2 years ago

@crux/store

@crux/store is an uncomplicated library with a succinct API that allows you to make and observe changes to a state object.

When subscribing, you provide a selector, which derives an arbitrary value from your state object, and a callback, which is called with the value returned from the selector.

Updating the state is really simple too. Just pass your new partial state to update(partialState: Partial<State>) and all affected callbacks will fire.

Installation

npm install --save @crux/store

Usage

Initialising the store

import { createStore } from '@crux/store';

interface State {
  users: User[];
}

interface User {
  username: string;
}

const store = createStore<State>({ users: [] });

Adding subscriptions

const unsubscribe = store.subscribe(getUsers, usersCallback);

/**
 * Selector to get the array of users from the state 
 */
function getUsers(state: State): User[] {
  return state.users;
}

/**
 * Callback to fire when the state.users array is updated 
 */
function usersCallback(users: User[]) {
  console.log(users);
}

Updating the state

store.update({ users: ['alice', 'bob', 'charlie'] });

// Console output:
// ['alice', 'bob', 'charlie']

You can also update a nested state by providing a target path as the second parameter.

interface State {
  topLevelState: {
    val: boolean,
    nestedState: {
      nestedVal: boolean,
    }
  }
}

store.update({ val: true }, 'topLevelState');
store.update({ nestedVal: true }, 'topLevelState.nestedState');

Unsubscribing

const unsubscribe = store.subscribe(getUsers, usersCallback);

unsubscribe();

store.update({ users: ['alice', 'bob', 'charlie'] });

// No console output

Pausing/resuming reactivity

@crux/store provides a way to batch updates by pausing and resuming the store. Any callbacks fired during the paused state are queued, and fired synchronously when the store is resumed.

store.pause();

store.update({ users: ['alice', 'bob', 'charlie'] });

// No console output

store.resume();

// Console output:
// ['alice', 'bob', 'charlie']
0.0.45-alpha

2 years ago

0.0.40-alpha

2 years ago

0.0.43-alpha

2 years ago

0.0.41-alpha

2 years ago

0.0.42-alpha

2 years ago

0.0.44-alpha

2 years ago

0.0.38-alpha

2 years ago

0.0.37-alpha

2 years ago

0.0.39-alpha

2 years ago

0.0.36-alpha

2 years ago

0.0.29-alpha

2 years ago

0.0.35-alpha

2 years ago

0.0.23

2 years ago

0.0.30-alpha

2 years ago

0.0.24

2 years ago

0.0.25

2 years ago

0.0.32-alpha

2 years ago

0.0.31-alpha

2 years ago

0.0.28-alpha

2 years ago

0.0.27-alpha

2 years ago

0.0.33-alpha

2 years ago

0.0.26

2 years ago

0.0.26-alpha

2 years ago

0.0.34-alpha

2 years ago

0.0.2

2 years ago

0.1.0-alpha

2 years ago

0.2.0-alpha

2 years ago

0.0.6

2 years ago

0.0.1

3 years ago