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>
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);
};
};
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>
In codepen, I can't write script in html view, anyway this is my pen link.
Top comments (0)