DEV Community

Discussion on: How State Management works? Dead simple SM in Vanilla JavaScript

Collapse
 
artydev profile image
artydev • Edited

Here is an optimised version :-)

import {render, html} from 'uhtml';

const App = (function () {

  const State = {
    counter : 0
  }

  function incer () {
    State.counter += 1;
    App.redraw()
  }

  function view () {
    return html`
      <h1>${State.counter}</h1>
      <button class="counter" onclick=${incer}>INC</button>
      <input value = "not erased"/>`
  }

  function redraw () {
    render(app, view())
  }

  return { redraw }

})()

App.redraw()




Enter fullscreen mode Exit fullscreen mode

You can test it here : SSMOPT

Collapse
 
artydev profile image
artydev

And if you want to get a little further

import {render, html} from 'uhtml';


const Header = () => html`<h1>Header</h1>`
const Footer = () => html`<h1>Footer</h1>`
const Counter = (state, actions) => html`
      <h1>${state.counter}</h1>
      <button class="counter" onclick=${actions.inc}>INC</button>
      <input value = "not erased"/>`

const App = (function () {

  const State = {
    counter : 0
  }

  const Actions = {
    inc : () =>  {
      State.counter += 1;
      redraw();
    }
  }

  function view (s, a) {
    return html`
      ${Header()}
      ${Counter(s, a)}
      ${Footer()}
    `
  }

  function redraw () {
    render(app, view(State, Actions))
  }

  return { redraw }

})()

App.redraw()

Enter fullscreen mode Exit fullscreen mode

You can test it here IntroSamPattern

Collapse
 
reenaverma profile image
Reena Verma

Hi @artydev- this is really interesting. I've not heard of the uthml package before. What exactly is it used/needed for vs the original package?