Skip to content

Instantly share code, notes, and snippets.

@mikansc
Created January 15, 2021 22:58
Show Gist options
  • Save mikansc/82ce013b45bad8c4d9b815260dac1309 to your computer and use it in GitHub Desktop.
Save mikansc/82ce013b45bad8c4d9b815260dac1309 to your computer and use it in GitHub Desktop.
Exemplo prático de Redux
console.clear();
// Action creators -------------------------------------------------//
// actions.js
const criarApolice = (nome, preco) => {
return {
//Action
type: 'NOVA_APOLICE',
payload: {
nome,
preco
}
}
};
const cancelarApolice = (nome) => {
return {
//Action
type: 'CANCELAR_APOLICE',
payload: {
nome
}
}
};
const registrarSinistro = (nome, indenizacao) => {
return {
//Action
type: 'REGISTRAR_SINISTRO',
payload: {
nome,
indenizacao
}
}
};
// Reducers -------------------------------------------------//
//--------------------- initial val -- payload --------------//
const historicoDeSinistros = (historicoDeSinistrosAtual = [], action) => {
if(action.type === 'REGISTRAR_SINISTRO') {
return [...historicoDeSinistrosAtual, action.payload];
}
return historicoDeSinistrosAtual;
};
// 2 --//
const financeiro = (saldoAtual = 100, action)=> {
if(action.type === 'REGISTRAR_SINISTRO') {
return saldoAtual - action.payload.indenizacao;
} else if (action.type === 'NOVA_APOLICE') {
return saldoAtual + action.payload.preco;
}
return saldoAtual;
};
// 3 --//
const apolices = (listaDeApolices = [], action) => {
if (action.type === 'NOVA_APOLICE') {
return [...listaDeApolices, action.payload.nome];
} else if (action.type === 'CANCELAR_APOLICE') {
return listaDeApolices.filter((nome)=> nome !== action.payload.nome);
}
return listaDeApolices;
};
// Store -------------------------------------------------//
const { createStore, combineReducers } = Redux;
const departamentos = combineReducers({
financeiro,
historicoDeSinistros,
apolices
});
const store = createStore(departamentos);
// // Testing our dispatch to store ------- //
// console.log(store.getState());
store.dispatch(criarApolice('Michael', 100));
store.dispatch(criarApolice('Emanuelle', 100));
store.dispatch(criarApolice('Rosane', 100));
store.dispatch(registrarSinistro('Michael', 300));
store.dispatch(cancelarApolice('Rosane'));
// Look how the store is now -----------//
console.log(store.getState());
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment