DEV Community

Cover image for Computed Nano Stores
Chris Bongers
Chris Bongers

Posted on • Originally published at

Computed Nano Stores

Now that we had a look at Maps with Nano Stores let's take a look at the next element, computed stores.

A computed store can take an initial static store and do some computing.
It can even compute from two different stores.

Nano Stores computed maps

If you'd like to follow this article, use this GitHub branch as your starting point.

The first thing we'll do is add a new value to our color objects called primary.
We can use this to determine if a color is a primary color.

Open up the src/store/colors.js file and change the color map.

const colors = map({
  blue: {
    primary: true,
    color: 'blue',
    hex: '#9bf6ff',
  green: {
    primary: false,
    color: 'green',
    hex: '#caffbf',
Enter fullscreen mode Exit fullscreen mode

Then we can start by adding the computed value list.
First, import it.

import { computed, map } from 'nanostores';
Enter fullscreen mode Exit fullscreen mode

Then we can use it. Since we are using a map, we have to extract the object values manually.
If you were using Atoms, you'd be able to loop directly over those.

const primaryColors = computed(colors, (list) =>
  Object.values(list).filter((item) => item.primary)
Enter fullscreen mode Exit fullscreen mode

Now let's go to our React.jsx component and add some more buttons to play with.

<button onClick={() => addColor('blue', '#a0c4ff', true)}>Change blue</button>
<button onClick={() => addColor('red', '#ffadad', true)}>Add red</button>
<button onClick={() => addColor('purple', '#bdb2ff', false)}>Add purple</button>
Enter fullscreen mode Exit fullscreen mode

Now, let's load the primary colors and assign them to a useStore.

import { primaryColors } from '../store/colors';

const primaryItems = useStore(primaryColors);
Enter fullscreen mode Exit fullscreen mode

Then under the existing list, we'll render the primary color list.

<h4>Primary colors</h4>
    {Object.values(primaryItems).map(({color, hex}) => (
        <li key={color} style={{ backgroundColor: hex }}>
            {color} {hex}
Enter fullscreen mode Exit fullscreen mode

You can now run your application. Try clicking the buttons. This click should result in both the map and computed list changing!

Computed map with Nano Stores

And as usual, you can also find the complete code on GitHub.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Oldest comments (0)