State management

Currently, in the Javascript ecosystem there are incredible state management libraries and for complex applications we recommend that you use one with Bemtv, however Bemtv also offers a simple way to manage the state, called “state functions”.

Bemtv believes that the Javascript modules already offer enough resources to manage the state, so stateFn() was created to take advantage of the javascript modules.

Basically, it is a function which can optionally function as both a getter and a setter and has a watch() method to allow you to watch the state.

import { stateFn } from "bemtv";

export const $theme = stateFn("dark");
// Seting
$theme("new theme");
// Geting
console.log($theme());

but if we need more control we can force our “stateFn” to work only as a getter and only allow the state to be changed through “actions”:

import { stateFn } from "bemtv";

const [$theme, setTheme] = stateFn("dark", true);

Note in the examples above that we pass a second argument true which tells stateFn() to return a function that works just like a getter.

Now the return of the stateFn() function is a tuple where the first item is a function that just gets the current value of the state and the second is a function to set the state.

Now let's use the javascript modules to provide isolation and create our “actions”:

import { stateFn } from "bemtv";

const [$theme, setTheme] = stateFn("dark", true);

export const toggleTheme = () => setTheme(isThemeDark() ? "light" : "dark");

export default $theme;

Note in the examples above the toggleTheme() function that changes the current theme, it is an “action” because taking advantage of having access to the setTheme() function with that it can change the state.

Another important thing is that we only export the “actions” and the $theme() function, which works like a normal function when called, just returning the current value without allowing the state to be changed.

stateFn().watch()

To react to state changes we can use the watch() method which accepts a callback/listener and fires it immediately and on each state change:

import { $theme } from "./state-fns/theme";

$theme.watch((currentValue) => {})

The listener also takes a second argument which is the number of times the listener has already been called:

import { $theme } from "./state-fns/theme";

$theme.watch((currentValue, count) => {
  console.log(currentValue, count);
});

To remove the listener just call the function returns by the watch() method:

import { $theme } from "./state-fns/theme";

const remove = $theme.watch((currentValue) => {})

remove()

Last updated