Skip to content

Instantly share code, notes, and snippets.

@luismartinezs
Last active July 30, 2022 06:43
Show Gist options
  • Save luismartinezs/524beb553eaad971a905c542660faace to your computer and use it in GitHub Desktop.
Save luismartinezs/524beb553eaad971a905c542660faace to your computer and use it in GitHub Desktop.
Redux toolkit slice #redux-toolkit
import React from "react";
import { Provider } from "react-redux";
import { store } from "./store";
function App() {
return (
<React.StrictMode>
<Provider store={store}>{/* App content */}</Provider>
</React.StrictMode>
);
}
export default App;
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
export interface IInitialState {
model: string | null;
color: string | null;
location: string | null;
averageRating: string | null;
}
const initialState: IInitialState = {
model: null,
color: null,
location: null,
averageRating: null,
};
export const dataSlice = createSlice({
name: "data",
initialState,
reducers: {
setData(state, action: PayloadAction<IInitialState>) {
state.model = action.payload.model;
state.color = action.payload.color;
state.location = action.payload.location;
state.averageRating = action.payload.averageRating;
},
resetData() {
return initialState;
},
clearDataItem(state, action: PayloadAction<keyof IInitialState>) {
state[action.payload] = null;
},
},
});
export default dataSlice.reducer;
export const { setData, resetData, clearDataItem } = dataSlice.actions;
import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import type { RootState, AppDispatch } from "./store";
// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch: () => AppDispatch = useDispatch;
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
import { FC } from 'react';
import { useAppSelector, useAppDispatch } from './hooks';
import {setData} from './dataSlice'
const SomeComponent: FC = () => {
const dispatch = useAppDispatch();
const data = useAppSelector((state) => state.data);
const handleSubmit = (newData) => {
dispatch(setData(newData));
};
return (
// some jsx
)
}
import { configureStore } from "@reduxjs/toolkit";
import { dataReducer } from "./dataSlice";
export const store = configureStore({
reducer: {
data: dataReducer,
},
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment