New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

corvid-storeon

Package Overview
Dependencies
Maintainers
1
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

corvid-storeon

A tiny event-based state manager Storeon for Corvid by Wix

2.5.0
Source
npm
Version published
Weekly downloads
2
Maintainers
1
Weekly downloads
 
Created
Source

corvid-storeon

corvid-storeon test status npm version minzip

Corvid Storeon

A tiny event-based state manager Storeon for Corvid by Wix.

How to use

You can use demo template or install from Package Manager.

  • Wix Website Template: Open In Editor
  • Install

Example

public/store.js

import { createStoreon } from "corvid-storeon";

const counter = (store) => {
  store.on("@init", () => ({ count: 0 }));
  store.on("increment", ({ count }) => ({ count: count + 1 }));
};

export const { getState, dispatch, connect, connectPage } = createStoreon([counter]);

Page Code

import { dispatch, connect, connectPage } from "public/store.js";

// Subscribe for state property "count".
// The callback function will be run when the page loads ($w.onReady())
// and each time when property "count" would change.
connect("count", ({ count }) => {
  $w("#text1").text = String(count);
});

// Wrapper around $w.onReady()
// The callback function will be run once.
connectPage((state) => {
  $w("#button1").onClick(() => {
    // Emit event
    dispatch("increment");
  });
});

Demo

Install

You use the Package Manager to manage the npm packages in your site.

Latest available version: v2.3.1 Check status

Install corvid-storeon

API

createStoreon

Creates a store that holds the complete state tree of your app and returns 4 methods for work with the app state.

Create store modules API.

const { getState, dispatch, connect, connectPage } = createStoreon(modules);

Syntax

function createStoreon(Array<Module | false>): Store

type Store = {
  getState: function
  dispatch: function
  connect: function
  connectPage: function
}

getState

Returns an object that holds the complete state of your app.

const state = getState();

Syntax

function getState(): object

dispatch

Emits an event with optional data.

dispatch("event/type", { value: 123 });

Syntax

function dispatch(event: string, [data: any]): void

connect

Connects to state by property key. It will return the function disconnect from the store.

const disconnect = connect("key", (state) => { });

disconnect();

You can connect for multiple keys, the last argument must be a function.

connect("key1", "key2", (state) => { });

Syntax

function connect(key: string, [key: string, ...], handler: ConnectHandler): Disconnect

callback ConnectHandler(state: object): void | Promise<void>

function Disconnect(): void

connectPage

Sets the function that runs when all the page elements have finished loading. (wrapper around $w.onReady())

connectPage((state) => { });

Syntax

function connectPage(initFunction: ReadyHandler): void

callback ReadyHandler(state: object): void | Promise<void>

Store

The store should be created with createStoreon() function. It accepts a list of the modules.

Each module is just a function, which will accept a store and bind their event listeners.

import wixWindow from "wix-window";
import { createStoreon } from "corvid-storeon";

// Business logic
function appModule(store) {
  store.on("@init", () => {
    return {
      items: [],
    };
  });

  store.on("items/add", ({ items }, item) => {
    return {
      items: [...items, item],
    };
  });
}

// Devtools
function logger(store) {
  store.on("@dispatch", (state, [event, data]) => {
    if (event === "@changed") {
      const keys = Object.keys(data).join(', ');
      console.log(`changed: ${keys}`, state);
    } else if (typeof data !== "undefined") {
      console.log(`action: ${event}`, data);
    } else {
      console.log(`action: ${event}`);
    }
  });
}

export default createStoreon([
  appModule,
  (wixWindow.viewMode === "Preview" && logger),
]);

Syntax

function createStoreon(Array<Module | false>): Store

function Module(store: StoreonStore): void

type StoreonStore = {
  get: function
  on: function
  dispatch: function
}

Storeon store methods

store.get

Returns an object that holds the complete state of your app. The app state is always an object.

const state = store.get();

Syntax

function get(): object
store.on

Adds an event listener. store.on() returns cleanup function. This function will remove the event listener.

const unbind = store.on("event/type", (state, data) => { });

unbind();

Syntax

function on(event: string, listener: EventListener): Unbind

callback EventListener(state: object, [data: any]): Result

function Unbind(): void

type Result = object | void | Promise<void> | false
store.dispatch

Emits an event with optional data.

store.dispatch("event/type", { value: "abc" });

Syntax

function dispatch(event: string, [data: any]): void

Events

There are 4 built-in events:

@init

It will be fired in createStoreon(). The best moment to set an initial state.

store.on("@init", () => { });
@ready

Added in: v2.0.0

It will be fired in $w.onReady() when all the page elements have finished loading.

store.on("@ready", (state) => { });
@dispatch

It will be fired on every new action (on dispatch() calls and @changed event). It receives an array with the event name and the event’s data. Can be useful for debugging.

store.on("@dispatch", (state, [event, data]) => { });
@changed

It will be fired when any event changes the state. It receives object with state changes.

store.on("@changed", (state, changes) => { });

You can dispatch any other events. Just do not start event names with @.

Reducers

If the event listener returns an object, this object will update the state. You do not need to return the whole state, return an object with changed keys.

// "products": {} will be added to state on initialization
store.on("@init", () => {
  return { products: { } };
});

Event listener accepts the current state as a first argument and optional event object as a second.

So event listeners can be a reducer as well. As in Redux’s reducers, you should change immutable.

store.on("products/save", ({ products }, product) => {
  return {
    products: { ...products, [product._id]: product },
  };
});
$w("#buttonAdd").onClick(() => {
  dispatch("products/save", {
    _id: uuid(),
    name: $w("#inputName").value,
  });
});

Async operations

You can dispatch other events in event listeners. It can be useful for async operations.

store.on("products/add", async (_, product) => {
  try {
    await wixData.save("Products",  product);

    store.dispatch("products/save", product);
  } catch (error) {
    store.dispatch("errors/database", error);
  }
});

License

MIT

Keywords

wix

FAQs

Package last updated on 27 Oct 2020

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