Rocket Logo Stoxy Docs Guides Toggle darkmode

Methods: Sub

Subscribe to updates in state of wanted object.

Allows you to programmatically react to state changes in wanted state objects

Params

NameAttribute
keyKey in string form. Used as the name of the state object
callbackCallback Function to call when state of given key is updated

Returns

Unsub function. The sub method adds event listeners to the DOM, so they need to be cleaned up to avoid memory leaks. Calling the returned unsub function will remove the listeners.

Usage

import { sub } from '@stoxy/core';

sub('shoppingcart', e => console.log('Shopping card updated. Current contents: ', e.data));

import { sub } from '@stoxy/core';

sub('shoppingcart', updateItemCount);

function updateItemCount(e) {
    write('itemcount', e.data.length);
}

import { sub } from '@stoxy/core';

const unsubber = sub('shoppingcart', updateItemCount);

function updateItemCount(e) {
    write('itemcount', e.data.length);
}

// Unsubscribe from events
unsubber();

Callback payload

The callback function is passed information about the event as a parameter, which can then be used to easily react to the change.

Callback params

NameAttribute
keyKey in string form. Used as the name of the state object
actionAction type or the update event (Update on content update, Delete on successful clear of said key)
dataCurrent data in said state

Usage

This can be used to easily react to the events happening with the state

import { sub } from '@stoxy/core';

sub('shoppingcart', onShoppingcartUpdate);

function onShoppingcartUpdate(e) {
    if (e.action === 'Update') {
        console.log('Shoppingcart updated');
    } else {
        console.log('Shoppingcart cleared');
    }

    fetch(myShoppingCardContentApiUrl, {
        method: 'POST',
        body: JSON.stringify(e.data),
    });
}