Skip to content

Instantly share code, notes, and snippets.

@Nick-Gabe
Created September 28, 2023 20:35
Show Gist options
  • Save Nick-Gabe/b7294b9d27bb2dd01622af766aa41879 to your computer and use it in GitHub Desktop.
Save Nick-Gabe/b7294b9d27bb2dd01622af766aa41879 to your computer and use it in GitHub Desktop.
React redux crud
import {configureStore, createSlice} from '@reduxjs/toolkit';
import {useDispatch, useSelector, Provider} from "react-redux"
// ------------------------------------------
// 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)
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 passaremos os reducers usados
reducer: configuracoesSlice.reducer
// caso tenha mais de um, passe como um objeto fazendo spread
// reducer: { ...A.reducer, ...B.reducer }
})
// ------------------------------------------
// ADICIONAR O PROVIDER DO REACT-REDUX
const App = () => {
return (
<Provider store={store}>
<Componente/>
</Provider>
)
}
// ------------------------------------------
const Componente = () => {
// LER UM ESTADO
const tema = useSelector(state => state.configuracoes.tema);
// ATUALIZAR UM ESTADO
const dispatch = useDispatch()
dispatch(
configuracoesSlice.actions.setarTema("escuro")
)
return <div/>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment