DEV Community

Larson
Larson

Posted on

js store: imus

imus

imus is a simple key-value store for javascript. Usable in frameworks or plain.

Even when writing small apps it's realy helpful to use stores. But most of the stores are to powerful and don't fit my needs.

Installation

npm install imus
Enter fullscreen mode Exit fullscreen mode

Usage in React Component

Listener

import { useEffect, useState } from "react";
import { subscribe, getStore } from "imus";

export default function TextComponent() {
    const [text, setText] = useState('');
    const unsubscribe = subscribe('myText', setText); // when key already exist, subscribe will call setText directly

    const [initText] = useState(getStore('myText') || '') // will also get the value, but wouldnt be updated

    useEffect(() => {
        return unsubscribe
    })
    return <p>{text}, {initText}</p>
}
Enter fullscreen mode Exit fullscreen mode

Dispatcher

import { dispatch } from "imus";

export default function InputComponent() {
    return <input onChange={(e) => dispatch('myText', e.target.value)} type="text"/>
}
Enter fullscreen mode Exit fullscreen mode

imus also allows to add getter and setter for the store. So you could just connect localStorage for example.

const setter = (store) => localStorage.setItem('store', JSON.stringify(store));
const getter = () => JSON.parse(localStorage.getItem('store'))

setConnector(setter, getter);
Enter fullscreen mode Exit fullscreen mode

Using HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <input onkeyup="updateText()" id="textInput" type="text" />
    <p id="textField"></p>
</head>
<body>
    <script src="https://unpkg.com/imus@1.3.0/dist/bundle.js">
    </script>
    <script>
        const unsubscribe = Imus.subscribe('myText', (value) => {
            document.getElementById('textField').innerHTML = value;
        });

        function updateText() {
            Imus.dispatch('myText', document.getElementById('textInput').value);
        }

    </script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Currently its work in progress but it works pretty well. The store is held in the imus package. In future it should also be possible to create stores. It should be possible to use imus even when your app grows.

Im not planing in creating another state management framework.

https://www.npmjs.com/package/imus

example with plain html:
https://notee.chimpsol.com/

Top comments (0)