Reputation: 69
I want to use 'useSelector' to select proper state of rootStore, but can't get state properly. The reason is auth reducer of RootState gives me type never.
How can I access any values from the user object properly?
My store looks like this :
export const store = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(thunk))
);
export const persistor = persistStore(store);
export default { store, persistor};
// Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
export type RootStore = ReturnType<typeof rootReducer>
export type AppDispatch = typeof store.dispatch;
My auth reducer looks like this :
import {
LOGIN_SUCCESS,
LOGIN_FAIL,
LOGIN_REQUEST,
LoginDispatchTypes,
} from "../actions/types";
import { User } from "../types/index";
interface initialStateI {
token: string;
isAuthenticated: boolean;
isLoading: boolean;
user?: User;
error: string;
}
const initialState = {
token: "",
isAuthenticated: false,
isLoading: false,
error: "",
};
export default function (
state: initialStateI = initialState,
action: LoginDispatchTypes
) {
switch (action.type) {
case LOGIN_REQUEST:
return {
...state,
isLoading: true,
};
case LOGIN_SUCCESS:
return {
...state,
isAuthenticated: true,
isLoading: false,
user: action.payload.user,
token: action.payload.access_token,
error: null,
};
case LOGIN_FAIL:
return {
...state,
isAuthenticated: false,
token: null,
user: null,
error: action.payload.message,
};
default:
return state;
}
}
My action looks like this :
export const LOGIN_SUCCESS = "LOGIN_SUCCESS";
export const LOGIN_FAIL = "LOGIN_FAIL";
export const LOGIN_REQUEST = "LOGIN_REQUEST";
import { User } from "../types/index";
export interface LoginSuccess {
type: typeof LOGIN_SUCCESS;
payload: {
expires_in: number;
user: User;
access_token: string;
token_type: string;
};
}
export interface LoginFail {
type: typeof LOGIN_FAIL;
payload: {
message: string;
};
}
export interface LoginRequest {
type: typeof LOGIN_REQUEST;
}
export type LoginDispatchTypes = LoginRequest | LoginFail | LoginSuccess;
This is how i try to display the user details on my view :
const { user : currentUser} = useSelector((state:RootState) => state.auth);
Also the type user is in this format:
export interface User {
email: string;
author_id: number;
}
Any advice or recommendations/useful links on how to access data from state will be highly appreciated.
Upvotes: 0
Views: 754
Reputation: 5479
You should use configureStore
from redux-toolkit
instead of createStore
if you do not want to add any additional typings
It seems this is what the redux team recommends https://redux.js.org/usage/usage-with-typescript#define-root-state-and-dispatch-types
Upvotes: 3