Skip to content

Instantly share code, notes, and snippets.

@Ifmr24
Created October 11, 2019 04:11
Show Gist options
  • Save Ifmr24/b4f87885e178101ee2d45e5690d38279 to your computer and use it in GitHub Desktop.
Save Ifmr24/b4f87885e178101ee2d45e5690d38279 to your computer and use it in GitHub Desktop.
React context api, reducers, hooks
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;
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