Skip to content

Instantly share code, notes, and snippets.

@gonzalovazquez
Created February 1, 2017 16:15
Show Gist options
  • Save gonzalovazquez/cf3bae2af2721d0836067fd2d5a6d7a1 to your computer and use it in GitHub Desktop.
Save gonzalovazquez/cf3bae2af2721d0836067fd2d5a6d7a1 to your computer and use it in GitHub Desktop.
A simple store with ReactJS
// Reducer:
// Specifies how the next state
// is calculated based on the
// current state and the action
// being dispatched
const counter = (state = 0,
action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
const { createStore } = Redux;
// Call createStore with
// counter as the reducer
// manages the state update
const store = createStore(counter);
/*
The store binds together the three
principles of Redux. It holds the
current application state object,
it lets you dispatch actions and
when you create it you need to specify
the reducer that tells how state
is updated with actions.
*/
// Retrives the current state of the
// redux store
console.log(store.getState());
// Lets you dispatch actions
// and change the state of your app
store.dispatch({type: 'INCREMENT'})
console.log(store.getState());
/*
Dumb component:
It does not contain any business logic.
Callback passed by props are passed
through event handlers.
*/
const Counter = ({
value,
onIncrement,
OnDecrement
}) => (
<div>
<h1>{value}</h1>
<button onClick={onIncrement}>+</button>
<button onClick={OnDecrement}>-</button>
</div>
);
const render = () => {
ReactDOM.render(
<Counter
value={store.getState()}
onIncrement = {() =>
store.dispatch({
type: 'INCREMENT'
})
}
OnDecrement = {() =>
store.dispatch({
type: 'DECREMENT'
})
}
/>,
document.getElementById('root')
);
};
/*
Lets you register a callback
The redux store will anytime
an action has been dispatched
so you can update the UI
to reflect the current application
state
*/
store.subscribe(render);
render();
// Dispatch event with click
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment