DEV Community

Pavel Kříž
Pavel Kříž

Posted on

Persistent variables in MithrilJS

This is my 13th write up on dev.to site. A simple way to use persistent variables in your app written in MithrilJS.

Mithril JS

Mithril JS is an excellent JS framework for writing web and mobile apps. It describes itself as:

Mithril.js is a modern client-side JavaScript framework for building Single Page Applications. It's small (8.9 KiB gzip), fast and provides routing and XHR utilities out of the box.

stream

There is an extension of Mithril JS called stream, which brings us reactive variables, as mentioned on it's site:

A Stream is a reactive data structure, similar to cells in spreadsheet applications.

You can use reactive variable as shown below:

var username = stream("John")
Enter fullscreen mode Exit fullscreen mode

persistent variables

By this term I mean a variable with persistent state (value), it keeps it's value even if you reload the page. Values are stored in localStorage.

I have an implementation of persistent stream() variables in Mithril JS. This code is NOT my work, I have asked AI for help and it creates me a solution.

function useStorage(key, defaultValue) {
  var initialValue = localStorage.getItem(key);
  if (initialValue === "null") {
    initialValue = null;
  } else if (initialValue === null || initialValue === undefined) {
    initialValue = defaultValue;
  }

  const stream = m.stream(initialValue);

  stream.map((value) => {
    if (value === null) {
      localStorage.setItem(key, "null");
    } else if (value === undefined) {
      localStorage.removeItem(key);
    } else {
      localStorage.setItem(key, value);
    }
    return value;
  });

  return stream;
}
Enter fullscreen mode Exit fullscreen mode

Simple example of declaration is like:

var input = useStorage("input", null);
Enter fullscreen mode Exit fullscreen mode

Function uses two parametres, the first one is a name for localStorage (keyName) and the second one is a value for localStorage (keyValue).

localStorage.setItem(keyName, keyValue)
Enter fullscreen mode Exit fullscreen mode

example of functional code

I have prepared a small sample on flems.io playground.

Hope this inspires you and helps you!

Top comments (0)