Redux

by Igor Cuckovic

JavaScript

/*
  the state tree
  a way to get the state tree // getState
  a way to listen and respond to the state changing // addListener
  a way to update the state // dispatch
  */
  
const createStore = (reducer) => {

	let state
  let listeners = []
  
  const getState = () => {
  	return state
  } 

	const addListener = (listener) => {
  	listeners.push(listener)
    return () => {
    	listeners = listeners.filter(l => l !== listener)
      console.log(listeners)
    }
  }
  
  const dispatch = (action) => {
  	state = reducer(state, action)
    listeners.forEach(l => l())
  }


	return {
  	getState,
    addListener,
    dispatch
  }

}  


////////




const reducer = (state = [], action) => {
	if (action.type === "ADD_TODO") {
  	return [...state, action.payload]
  }
}

const store = createStore(reducer)

store.addListener(() => {
	console.log("The new state is: " + store.getState())
})

store.dispatch({
	type: "ADD_TODO",
  payload: "Get milk!"
})

store.dispatch({
	type: "ADD_TODO",
  payload: "Get bread!"
})

console.log(store.getState())