Redux

by Igor Cuckovic

HTML

<div id="root"></div>
<button id="dugme"> dugme</button>

JavaScript

const createStore = (reducer) => {

  /*
  the state tree
  a way to get the state tree
  a way to listen and respond to the state changing
  a way to update the state
  */
	
  let state
  let listeners = []
  
  const getState = () => {
  	return state
  }
  
  const subscribe = (listener) => {
  	listeners.push(listener)
  }
  
  const dispatch = (action) => {
  	state = reducer(state, action)
    listeners.forEach(listener => listener())
  }
  
  
	return {
  	getState,
    subscribe,
    dispatch
  }
}

////


let reducer = (state = {krumpir: 0, mrkva: 0}, action) => {
	if (action.type === "DODAJ_KRUMPIR") {
  	return {
    	...state, 
     	krumpir: state.krumpir + action.kolicina
      }
  }
  
  	if (action.type === "DODAJ_MRKVU") {
  	return {
    	...state, 
     	mrkva: state.mrkva + action.kolicina
      }
  }
  
  return state
}

let store = createStore(reducer)

store.subscribe(() => {
	console.log(store.getState())
})

store.dispatch({type: "DODAJ_KRUMPIR", kolicina: 1})

store.dispatch({type: "DODAJ_MRKVU", kolicina: 2})
store.dispatch({type: "bezveze", kolicina: 2})

document.getElementById("dugme").onclick = () => store.dispatch({type: "DODAJ_KRUMPIR", kolicina: 2})