SolidJS Stores And The Path Pattern Syntax
How to use and understand the SolidJS path pattern syntax to update state in your store
There are different ways for state managment in SolidJS, one of them is to use a Store.
In this example we create a Store for a fruit shop, the Store has 3 different products.
import { render } from "solid-js/web";
import { createStore } from "solid-js/store";
function FruitList() {
const [state, setState] = createStore({
products: [
{ name: 'Red Apple ๐', price: 0.55, available: true},
{ name: 'Green Apple ๐', price: 0.55, available: false },
{ name: 'Pineapple ๐', price: 1.09, available: true },
]
});
return (
<div>
<ul>
{state.products.map(product => (
<li>
{`${product.name} - ${product.price}$ - ${product.available ? "โ
" : "โ"}`}
</li>
))}
</ul>
</div>
);
}
render(() => <FruitList />, document.getElementById("app")!);
This component renders a list of all the fruits from the products array in the store.
/// output
* Red Apple ๐ - 0.55$ - โ
* Green Apple ๐ - 0.55$ - โ
* Pineapple ๐ - 1.09$ - โ
setState with the Path Pattern
We created our Store with the ES6 destructing assignment syntax.
The setState function from our Store allows us to change the data in our Store and cause an update in the UI. Since the data in our store is an object, every key has to be unique. Because every key is unique we can tell our setState function through the key which data we want to update. SolidJS gives us a neat way to update our data in our Store with their Path Pattern Syntax.
You can pass different parameters into the setState function, the last parameter is the new value. The parameters before the new value are different ways to describe the path to the data you want to change.
For example:
With an index
setState("products", 1, "available", true)
This syntax can be read like this:
update the data where
- the key is "products",
- the item has the index 1,
- the key in the item is "available"
to new data => true
Output:
* Red Apple ๐ - 0.55$ - โ
* Green Apple ๐ - 0.55$ - โ
* Pineapple ๐ - 1.09$ - โ
With an array
The second parameter can also be an array.
setState("products", [0, 2], "available", false)
This syntax can be read like this:
update the data where:
- the key is "products",
- the items have the index 0 and 2,
- the key from the items is "available"
to new data => false
Output:
* Red Apple ๐ - 0.55$ - โ
* Green Apple ๐ - 0.55$ - โ
* Pineapple ๐ - 1.09$ - โ
With a callback function
You can also give it a callback function.
setState("products", {}, product => ({available: !product.available}))
This syntax can be read like this:
update the data where:
- the key is "products"
and run this function: product => ({available: !product.available})) on every item
Output:
* Red Apple ๐ - 0.55$ - โ
* Green Apple ๐ - 0.55$ - โ
* Pineapple ๐ - 1.09$ - โ
This should give you a small overview of what you can do with the path pattern and how to understand it, to find more complex examples and informations you can read the official docs.