Created
May 18, 2022 01:19
-
-
Save csorlandi/1bd1f33315fb76c6eb62e1b1e49cb6e4 to your computer and use it in GitHub Desktop.
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 { useReducer } from 'react'; | |
const initialState = { | |
counter: 0, | |
}; | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case 'INCREMENTAR': | |
return { | |
counter: state.counter + action.payload, | |
}; | |
case 'DECREMENTAR': | |
return { | |
counter: state.counter - 1, | |
}; | |
case 'REINICIAR': | |
return { | |
counter: action.payload, | |
} | |
default: | |
return state; | |
} | |
}; | |
export default function Contador() { | |
const [state, dispatch] = useReducer(reducer, initialState); | |
return ( | |
<> | |
<h1>A contagem é {state.counter}</h1> | |
<div> | |
<button onClick={() => dispatch({ | |
type: 'DECREMENTAR' | |
})}>Decrementar</button> | |
<button onClick={() => dispatch({ | |
type: 'INCREMENTAR', | |
payload: 1, | |
})}>Incrementar +1</button> | |
<button onClick={() => dispatch({ | |
type: 'INCREMENTAR', | |
payload: 2, | |
})}>Incrementar +2</button> | |
<button onClick={() => dispatch({ | |
type: 'REINICIAR', | |
payload: 0, | |
})}>Reiniciar</button> | |
</div> | |
</> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment