Skip to content

Instantly share code, notes, and snippets.

@zxcfer
Last active May 15, 2020 14:44
Show Gist options
  • Save zxcfer/07ae6f75bdd7ccb5ea693d7e026a6e2a to your computer and use it in GitHub Desktop.
Save zxcfer/07ae6f75bdd7ccb5ea693d7e026a6e2a to your computer and use it in GitHub Desktop.
Contador Redux
import React from 'react';
import logo from './logo.svg';
import './App.css';
import { Provider, useSelector, useDispatch } from 'react-redux'
import { createStore } from 'redux'
const rootReducer = (state = {count: 0}, action) => {
switch(action.type) {
case 'INCREMENTAR_CONTADOR':
return { ...state, count: state.count + 1}
case 'DECREMENTAR_CONTADOR':
return { ...state, count: state.count - 1}
case 'RESETEAR_CONTADOR':
return { ...state, count: 0 }
default:
return state
}
}
const store = createStore(rootReducer)
function Contador() {
// trae al propiedad `count` del store
const count = useSelector(state => state.count)
// define el despachador
const dispatch = useDispatch()
// definir mis acciones
const incrementarContador = { type: "INCREMENTAR_CONTADOR" }
const decrementarContador = { type: "DECREMENTAR_CONTADOR" }
const resetearContador = { type: "RESETEAR_CONTADOR", value: 0 }
return <div>
<h2>Contador: {count}</h2>
<button onClick={()=>dispatch(incrementarContador)}>Incrementar</button>
<button onClick={()=>dispatch(decrementarContador)}>Decrementar</button>
<button onClick={()=>dispatch(resetearContador)}>Reset</button>
</div>
}
function App() {
return (
<Provider store={store}>
<div className="App">
<h1>Contador Redux</h1>
<Contador />
</div>
</Provider>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment