DEV Community

loading...

Unistore : a nice little observable state container

artydev profile image artydev Updated on ・1 min read

Unistore :

A tiny 350b centralized state container with component bindings for Preact & React

But you can use it in vanilla JS.

Here is a demo unistore

<script src="https://unpkg.com/unistore/dist/unistore.umd.js"></script>
Enter fullscreen mode Exit fullscreen mode


const store = unistore({
  count : 0,
  ch :  () => Math.random() < 0.5 ? "🏓" : "🎳"         
})

const inc = store.action(
  function (s, i) {  
   return { count: s.count + i }  
})

async function sleep (ms) {
  return new Promise((res, err) => { 
      setTimeout(res, ms) 
  })
}

function log (message) {
  let elt = document.createElement("div")  
  elt.innerHTML = `${message} - (${store.getState().count})`
  logger.appendChild(elt)
} 

function demo () {
  logger.innerHTML = "";
  (async () => { 
    for(i = 0; i < 7; i++) { 
      await sleep(120)
      inc(1)
    }
  })()   
}

store.subscribe( state => log(state.ch())); 

Enter fullscreen mode Exit fullscreen mode

Another Example :

Discussion (0)

Forem Open with the Forem app