Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import {
configureStore,
createSlice,
createAsyncThunk,
PayloadAction,
getDefaultMiddleware,
} from "@reduxjs/toolkit";
import { useDispatch, useSelector } from "react-redux";
import logger from "redux-logger";
type CounterState = {
value: number;
hasError: boolean;
};
const addAsync = createAsyncThunk<number, number>(
"add-async",
async (input) => input
);
export const counterSlice = createSlice({
name: "counter",
initialState: { value: 0, hasError: true } as CounterState,
reducers: {
add(state, { payload }: PayloadAction<number>) {
state.value = state.value + payload;
},
},
extraReducers: (builder) => {
builder.addCase(addAsync.fulfilled, (state, { payload }) => {
state.value = payload;
state.hasError = false;
});
builder.addCase(addAsync.rejected, (state) => {
state.hasError = true;
});
},
});
export function configure() {
return configureStore({
reducer: {
counter: counterSlice.reducer,
},
middleware: getDefaultMiddleware().concat(logger),
});
}
type Store = ReturnType<typeof configure>;
type AppDispatch = Store["dispatch"];
export type RootState = ReturnType<Store["getState"]>;
export const useAppSelector = <T>(selector: (s: RootState) => T) =>
useSelector<RootState>(selector);
export const useAppDispatch = () => useDispatch<AppDispatch>();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment