Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a state management solution for lit-element?

If there is a list which should be rendered from an array, and the array will be passed from the grand-grand-grand-grand-grand-parent custom element. That will be super annoying.

Is there a global state management solution for lit-element, just like redux?

like image 742
zzzgoo Avatar asked Aug 08 '19 09:08

zzzgoo


People also ask

What is state management in JavaScript?

State management is the core of any modern web application, as it determines what data is displayed on the screen during the app usage session while the user interacts with it.


2 Answers

LitElement is a library and you can use any library for state management that you want. Just subscribe to the store in the constructor or connectedCallback (unsubscribe in disconnectedCallback) and change the components' properties when the store notifies you of a change.

Here you have some PWA helpers that works with litElement and you have one for Redux.

https://github.com/Polymer/pwa-helpers#connect-mixinjs

like image 55
jorgecasar Avatar answered Sep 28 '22 10:09

jorgecasar


Yes, check out LitState (npm package name lit-element-state).

I created this specially for LitElement. It has the same mindset: simple, small and powerful.

Because it is created specially for LitElement, it integrates very well and therefore the usage is very simple. You make a state object like this:

import { LitState, stateVar } from 'lit-element-state';

class MyState extends LitState {
    @stateVar() myCounter = 0;
}

export const myState = new MyState();

Usage without @decorators, look here.

Then you can use the state in your components like this:

import { LitElement, html } from 'lit-element';
import { observeState } from 'lit-element-state';
import { myState } from './my-state.js';

class MyComponent extends observeState(LitElement) {

    render() {
        return html`
            <h1>Counter: ${myState.counter}</h1>
            <button @click=${() => myState.counter++}></button>
        `;
    }

}

When you add the observeState() mixin to your component, the component will automatically re-render when any stateVar they use changes. You can do this with any amount of component and states and it will all automatically stay synchronized thanks to the observeState() mixin.

like image 27
gitaarik Avatar answered Sep 28 '22 10:09

gitaarik