Created
October 11, 2019 04:11
-
-
Save Ifmr24/b4f87885e178101ee2d45e5690d38279 to your computer and use it in GitHub Desktop.
React context api, reducers, hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useReducer } from "react"; | |
import * as TheReducer from "./Context/context"; | |
function ComoUsarReducer() { | |
const [state, dispatch] = useReducer( | |
TheReducer.default, | |
TheReducer.initialState | |
); | |
return ( | |
<> | |
<div>{state.contador}</div> | |
<div className="buttons"> | |
<button onClick={() => dispatch({ type: "SUMAR_1" })}> Sumar 1 </button> | |
<button onClick={() => dispatch({ type: "RESTAR_1" })}> Restar 1 </button> | |
</div> | |
</> | |
); | |
} | |
export default App; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const initialState = { | |
loading: false, | |
data: [], | |
error: null, | |
contador: 0 | |
}; | |
const reducer = (state = initialState, action) => { | |
const { contador } = state; | |
switch (action.type) { | |
case "SUMAR_1": | |
return Object.assign({}, state, { | |
contador: contador + 1 | |
}); | |
case "RESTAR_1": | |
return Object.assign({}, state, { | |
contador: contador - 1 | |
}); | |
default: | |
return state; | |
} | |
}; | |
export default reducer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment