Utility to parse and update Shopify collection URLs to help handle AJAX tag filtering and sorting. Similar to Liquid's link_to_add_tag
and link_to_remove_tag
, but for JavaScript.
npm i shopify-collection --save
or
yarn add shopify-collection
Only need to initialize a collection once.
import manage from 'shopify-collection';
// Initialize with a url, by default will use `window.location.href`
const collection = manage(URL);
getState()
Return the current state of the collection. Every method also has a callback that returns the value of getState()
.
// Current url:
// https://store.myshopify.com/collections/tops/color_blue?sort_by=manual
collection.getState();
{
handle: 'tops',
page: 1,
sort_by: 'manual',
tags: ['color_blue'],
url: 'https://store.myshopify.com/collections/tops/color_blue+color_black?sort_by=manual'
}
addTags([tags], func(state))
// Current url:
// https://store.myshopify.com/collections/tops/color_blue
collection.addTags(['array_of', 'tag_to', 'add'], state => {});
Returned state
:
{
handle: 'tops',
page: 1,
sort_by: null,
tags: ['color_blue', 'array_of', 'tags_to', 'add'],
url: 'https://store.myshopify.com/collections/tops/color_blue+array_of+tags_to+add'
}
removeTags([tags], func(state))
// Current url:
// https://store.myshopify.com/collections/tops/color_blue+size_small+fit_standard
collection.removeTags(['size_small', 'color_blue'], state => {});
Returned state
:
{
handle: 'tops',
page: 1,
sort_by: null,
tags: ['fit_standard'],
url: 'https://store.myshopify.com/collections/tops/fit_standard'
}
setSort(method, func(state))
method
should be one of manual
, best-selling
, title-ascending
, title-descending
, price-ascending
, price-descending
, created-ascending
, created-descending
.
// Current url:
// https://store.myshopify.com/collections/tops/color_blue
collection.setSort('best-selling', state => {});
Returned state
:
{
handle: 'tops',
page: 1,
sort_by: 'best-selling',
tags: ['color_blue'],
url: 'https://store.myshopify.com/collections/tops/fit_standard?sort_by=best-selling'
}
clearSort(func(state))
// Current url:
// https://store.myshopify.com/collections/tops/color_blue?sort_by=manual
collection.clearSort(state => {});
Returned state
:
{
handle: 'tops',
page: 1,
sort_by: null,
tags: ['color_blue'],
url: 'https://store.myshopify.com/collections/tops/fit_standard'
}
clearAll(func(state))
Remove all active tag filters and sort
// Current url:
// https://store.myshopify.com/collections/tops/color_blue?sort_by=manual
collection.clearSort(state => {});
Returned state
:
{
handle: 'tops',
page: 1,
sort_by: null,
tags: [],
url: 'https://store.myshopify.com/collections/tops'
}