Skip to content

Instantly share code, notes, and snippets.

@luizomf
Created February 16, 2021 19:11
Show Gist options
  • Save luizomf/f15e004234daf510e9885568b6c1b9c9 to your computer and use it in GitHub Desktop.
Save luizomf/f15e004234daf510e9885568b6c1b9c9 to your computer and use it in GitHub Desktop.
React Hook useReducer - Curso React
import { useReducer } from 'react';
import './App.css';
const globalState = {
title: 'O título que contexto',
body: 'O body do contexto',
counter: 0,
};
const reducer = (state, action) => {
switch (action.type) {
case 'muda': {
console.log('Chamou muda com', action.payload);
return { ...state, title: action.payload };
}
case 'inverter': {
console.log('Chamou inverter');
const { title } = state;
return { ...state, title: title.split('').reverse().join('') };
}
}
console.log('NENHUMA ACTION ENCONTRADA...');
return { ...state };
};
function App() {
const [state, dispatch] = useReducer(reducer, globalState);
const { counter, title, body } = state;
return (
<div>
<h1>
{title} {counter}
</h1>
<button
onClick={() =>
dispatch({
type: 'muda',
payload: new Date().toLocaleString('pt-BR'),
})
}
>
Click
</button>
<button onClick={() => dispatch({ type: 'inverter' })}>Invert</button>
<button onClick={() => dispatch({ type: 'QUALQUERCOiSA' })}>
SEM ACTION
</button>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment