Redux explenation

mail@pastecode.io avatar
unknown
javascript
2 years ago
1.0 kB
2
Indexable
Never
// actions.js
const addPost = (title, body) => ({
	type: ADD_POST,
	payload: {
		title,
		body
	}
});


// reducer.js
function reducer(state=[], action){
	switch(action.type){
		case ADD_POST:
			return [...state, action.payload]
	}
	return state;
}

// store.js
function createStore(reducerFunction, initialState) {
	let currentState = initialState;
	let listeners = [];
	return {
		dispatch() {
			currentState = reducerFunction(currentState, action);
			listeners.forEach((listenerFunction) => listenerFunction());
		},
	getState() {
		return currentState;
	},
	subscribe(listener) {
		listeners.push(listener);
		return function () {
			listeners = listeners.filter((currentListener) => currentListener !== listener)
		}
		}
	}
}


const store = createStore(reducer);


// Components
store.dispatch(addPost("What is Redux", "Hey do you know guys what is redux?"));
store.dispatch(addPost("I <3 Redux", "Guys I wanted to share with you, that I have left my girlfriend for Redux, its fucking awesome!"));