Skip to content

Instantly share code, notes, and snippets.

@guangLess
Created October 15, 2017 03:42
Show Gist options
  • Save guangLess/e96630a6db3beb6dbfce6503e1896a65 to your computer and use it in GitHub Desktop.
Save guangLess/e96630a6db3beb6dbfce6503e1896a65 to your computer and use it in GitHub Desktop.
const counter = (state = 0, action) => {
switch (action.type){
case 'INCREMENT' :
return state + 1;
case 'DECREMENT' :
return state -1;
default:
return state;
}
}
const Counter = ({
value,
onIncrement,
onDecrement
}) => (
<div>
<h1>{value}</h1>
<button onClick={onIncrement}>+</button>
<button onClick={onDecrement}>-</button>
</div>
);
const {createStore} = Redux;
// same as ----> import { createStore } from 'redux'
const store = createStore(counter);
const render = () => {
//console.log("inside of render == ",store.getState());
// document.body.innerText = store.getState();
ReactDOM.render(
<Counter value={store.getState()}
onIncrement={() =>
store.dispatch({
type:'INCREMENT'
})
}
onDecrement={()=>
store.dispatch({
type:'DECREMENT'
})
}
/>,
document.getElementById('root')
);
}
store.subscribe(render);
render();
// document.addEventListener('click', () => {
// store.dispatch({type: 'INCREMENT'});
// })
// store.subscribe(render);
// render()
// document.addEventListener('click', () => {
// store.dispatch({type:'INCREMENT'});
// });
// console.log(store.getState());
// const createStore = (reducer) => {
// let state;
// let listeners = [];
// const getState = () => state;
// const dispatch = (action) => {
// state = reducer(state, action)
// listeners.forEach(listener => listener());
// };
// const subscribe = (listener) => {
// listener.push(listener);
// return () => {
// listeners = listeners.filter(l => l !== listener);
// };
// };
// dispatch({});
// return {getState, dispatch, subscribe}
// }
@guangLess
Copy link
Author

compositions

const todo = (state, action) => {
switch (action.type) {
case 'ADD_TODO':
return {
id: action.id,
completed:false,
};
case 'TOGGLE_TODO':
if(state.id !== action.id){
return state;
}
return {
...state,
completed: !todo.completed
}
default:
return state;
}
}

const todos = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
todo(undefined, action)
];
case 'TOGGLE_TODO':
return state.map(t => todo(t,action))
default:
return state;
}
};

const togggleAction = {
type: 'TOGGLE_TODO',
id:1
}

const preState = [{
id:1,
completed:false,
text: 'Learn Redux'
},
{
id:0,
completed:false,
text: 'Getting it'
}
]

console.log(todos(preState, togggleAction))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment