Basic implementation of how Redux works
const redux = require('redux');
const createStore = redux.createStore;
const initialState = {
counter: 0
}
//Reducer
const rootReducer = (state = initialState, action) => {
if (action.type === 'INC_COUNTER') {
return {
...state,
counter: state.counter + 1
}
}
if (action.type === 'ADD_COUNTER') {
return {
...state,
counter: state.counter + action.value
}
}
return state;
}
//Store
const store = createStore(rootReducer);
console.log(store.getState());
//Subscription(calls function passed to it every time an action is beeing dispatched)
store.subscribe(() => {
console.log('[Subscription]', store.getState());
})
//Dispatching Action
store.dispatch({type: 'INC_COUNTER'});
store.dispatch({type: 'ADD_COUNTER', value: 10});
console.log(store.getState());
import * as actionTypes from './actions';
const initialState = {
counter: 0,
results: []
}
const reducer = (state = initialState, action) => {
switch (action.type) {
case actionTypes.INCREMENT:
return {
...state,
counter: state.counter + 1
}
case actionTypes.DECREMENT:
return {
...state,
counter: state.counter - 1
}
case actionTypes.ADD:
return {
...state,
counter: state.counter + action.val
}
case actionTypes.SUBTRACT:
return {
...state,
counter: state.counter - action.val
}
case actionTypes.STORE_RESULT:
return {
...state,
results: state.results.concat({id: new Date(), value: state.counter})
}
case actionTypes.DELETE_RESULT:
// const id = 2;
// const newArray = [...state.results];
// newArray.splice(id, 1);
const updatedArray = state.results.filter(result => result.id !== action.resultId)
return {
...state,
results: updatedArray
}
}
return state;
}
export default reducer;