JavaScript SDK store

Snipcart's JavaScript SDK uses Redux as a state management tool. Therefore, some Redux store methods are available.

getState

The getState method returns the current state tree of the application. In this case, the return value is of type SnipcartState.

Snipcart.store.getState();

subscribe

The subscribe method triggers a callback every time an action is dispatched. It is often used to check if a change occurred in the state of the application. When invoked, the return function of the subscribe method will remove the change listener.

let currentValue;
const unsubscribe = store.subscribe(() => {
    let previousValue = currentValue;
    currentValue = Snipcart.store.getState();

    if (previousValue !== currentValue) {
        // Anything goes...
    }
});

// unsubscribe();

Items count

If you need to display the items count programmatically, you can access it through the state:

Snipcart.store.getState().cart.items.count

A common use case of this would be to update a div that contains the items count:

// Let's say you have a <div id="cart-items-count" /> in your application.

const div = document.getElementById('cart-items-count');

Snipcart.store.subscribe(() => {
  const count = Snipcart.store.getState().cart.items.count;
  div.innerHTML = count;
});

Was this article helpful?