DEV Community

Cover image for Simple state management in RoR html.erb files
Zaw Htut Win
Zaw Htut Win

Posted on

Simple state management in RoR html.erb files

The issue I was trying to solve was that I wanted to use state management and I was coding in Rails. Rails's views html.erb are so convenient to work with, on the other hand state management in frameworks like React are really enticing. Since I chose Rails views, I lose the power of state management. So I researched about simple state management tool asking Chat Gpt. Then I came to know the answer, redux.js.

index.html

<html>
<body>
    <input id="myname" type="text" width="200px" />
    <span id="repeatMyName"></span>
  <span id="repeatMyName2"></span>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In here I was declaring, a Reducer(a place where I can set the variable of the state)
,which is called myReducer.

store.js

function myReducer(state=[],action){
  switch(action.type){
    case 'SET_MY_NAME':
      return {...state,myName:action.payload}
    default:
      return state;
  }
}

function createStore(reducer) {
    let state;
    let listeners = [];

    const getState = () => state;

    const dispatch = (action) => {
      state = reducer(state, action);
      listeners.forEach(listener => listener());
    };

    const subscribe = (listener) => {
      listeners.push(listener);
      return () => {
        listeners = listeners.filter(l => l !== listener);
      };
    };
Enter fullscreen mode Exit fullscreen mode

Back to index.html, I can start using state like this
index.html

<script>
$(document).ready(function(){

  $("#myname").on('keyup',function(event){
      store.dispatch({ type: 'SET_MY_NAME', payload: event.target.value});
    });

  store.subscribe(() => {
    const currentState = store.getState();
    $('#repeatMyName').text(currentState.myName);
    $('#repeatMyName2').text(currentState.myName);
  });

})  
</script>
Enter fullscreen mode Exit fullscreen mode

In codepen, I can't write script in html view, anyway this is my pen link.

https://codepen.io/zawhtutwin/pen/wvQZYxK

Top comments (0)