Skip to content

Instantly share code, notes, and snippets.

@Nick-Gabe
Created September 28, 2023 20:31
Show Gist options
  • Save Nick-Gabe/755b76d8e87f0731e4cd62f8b47c9aa7 to your computer and use it in GitHub Desktop.
Save Nick-Gabe/755b76d8e87f0731e4cd62f8b47c9aa7 to your computer and use it in GitHub Desktop.
redux toolkit crud
import {
configureStore,
createSlice
} from '@reduxjs/toolkit';
// ------------------------------------------
// CONFIGURAR SEU SLICE
const configuracoesSlice = createSlice({
name: 'configuracoes',
// propriedades que iniciarão por padrão
initialState: {
tema: "claro",
notificacoes: false
},
// funções que modificam o estado
reducers: {
// state é o slice atual
// action.payload é o valor recebido
setarTema: (state, action) => {
state.tema = action.payload
},
setarNotificacoes: (state, action) => {
state.notificacoes = action.payload
}
}
});
// ------------------------------------------
// CONFIGURAR SUA STORE
const store = configureStore({
// aqui passamos os reducers usados
reducer: configuracoesSlice.reducer
// caso tenha mais de um, passe como um objeto fazendo spread
// reducer: { ...A.reducer, ...B.reducer }
})
// ------------------------------------------
// LER UM ESTADO
tema = store.getState().configuracoes.tema
// ------------------------------------------
// MODIFICAR UM ESTADO
// Use o dispatch para salvar a modificação
store.dispatch(
// Use a action passando o novo valor
configuracoesSlice.actions.setarTema("escuro")
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment