Looking to improve my understanding of Redux-Toolkit, I've encountered some dispatch errors.
authSlice.ts
import { createAppSlice } from "@/lib/createAppSlice";
import type { PayloadAction } from "@reduxjs/toolkit";
export interface IAuthState {
authState: boolean;
}
const initialState: IAuthState = {
authState: false,
};
export const authSlice = createAppSlice({
name: "auth",
initialState,
reducers: {
setAuthState: (state, action: PayloadAction<boolean>) => {
state.authState = action.payload;
},
},
});
export const { setAuthState } = authSlice.actions;
export const authReducer = authSlice.reducer;
store.ts
import type { Action, ThunkAction } from "@reduxjs/toolkit";
import { combineSlices, configureStore } from "@reduxjs/toolkit";
import { counterSlice } from "./features/counter/counterSlice";
import { quotesApiSlice } from "./features/quotes/quotesApiSlice";
import { authSlice } from "./features/auth/authSlice";
const rootReducer = combineSlices(counterSlice, quotesApiSlice, authSlice);
export type RootState = ReturnType<typeof rootReducer>;
export const makeStore = () => {
return configureStore({
reducer: rootReducer,
middleware: (getDefaultMiddleware) => {
return getDefaultMiddleware().concat(quotesApiSlice.middleware);
},
});
};
export type AppStore = ReturnType<typeof makeStore>;
export type AppDispatch = AppStore["dispatch"];
export type AppThunk<ThunkReturnType = void> = ThunkAction<
ThunkReturnType,
RootState,
unknown,
Action
>;
hooks.ts
// Centralizing pre-typed Redux hooks for easy re-export.
import { useDispatch, useSelector, useStore } from "react-redux";
import type { AppDispatch, AppStore, RootState } from "./store";
// Enhanced versions of `useDispatch` and `useSelector` used throughout the app
export const useAppDispatch = useDispatch.withTypes<AppDispatch>();
export const useAppSelector = useSelector.withTypes<RootState>();
export const useAppStore = useStore.withTypes<AppStore>();
authUpdater.tsx
This file is where the dispatch function is being utilized.
import React from "react";
import { setAuthState } from "@/lib/features/auth/authSlice";
import { useAppDispatch } from "@/lib/hooks";
export const AuthUpdater = () => {
const dispatch = useAppDispatch();
return (
<div>
<button onClick={() => dispatch(setAuthState(true))}>Log in</button>
<button onClick={() => dispatch(setAuthState(false))}>Log out</button>
</div>
);
};
Encountering errors with the dispatch function:
react_redux__WEBPACK_IMPORTED_MODULE_0__.useDispatch.withTypes is not a function