Skip to content

Instantly share code, notes, and snippets.

@mikansc
Created January 15, 2021 23:10
Show Gist options
  • Save mikansc/3934258c11fcf057da67b500ae69f73b to your computer and use it in GitHub Desktop.
Save mikansc/3934258c11fcf057da67b500ae69f73b 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;
};
//---------------- initial val ------ payload --------------------------//
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;
};
//--------------- initial val --------- payload -------------------------//
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 (onde fica nosso state) ----------------------------------------//
const { createStore, combineReducers } = Redux;
const departamentos = combineReducers({
financeiro,
historicoDeSinistros,
apolices
});
const store = createStore(departamentos);
// // Comandos para testar nossa store e nossas actions ------- //
console.log('Estado inicial:', store.getState());
// uncomment the desired action and see the result at console --//
store.dispatch(criarApolice('Michael', 500));
// store.dispatch(criarApolice('Emanuelle', 100));
store.dispatch(criarApolice('Rosane', 100));
// store.dispatch(registrarSinistro('Michael', 300));
store.dispatch(cancelarApolice('Rosane'));
// Olhe o resultado da store -----------//
console.log('Estado final:', 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