Redux explenation
unknown
javascript
3 years ago
1.0 kB
9
Indexable
// 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!"));
Editor is loading...