Home > front end >  Redux useSelector does not infer state properly --- Typescript
Redux useSelector does not infer state properly --- Typescript

Time:07-28

Would love to know how to infer my state on the useSelector hook

import { applyMiddleware, createStore } from 'redux';
    import thunk from 'redux-thunk';
    
    import { reducers } from './reducers';
    
    export const store = createStore(reducers, {}, applyMiddleware(thunk));
    
    export type RootState = ReturnType<typeof reducers>;

Want to use it in my component like so

const { LogoutUser } = bindActionCreators(actionCreators, dispatch);
const appState = useSelector((state: RootState) => state.auth);

{appState.isAuthenticated && (
              <Button
                onClick={handleUserLogout}
                size={'sm'}
                colorScheme={'red'}
              >
                Logout
              </Button>
            )}

Typescript is annoyed

 Error Property 'isAuthenticated' does not exist on type 'never'.

My State

export const initialState: IState | undefined = {
  user: null,
  isAuthenticated: false,
};

CodePudding user response:

Have you try to create your own useSelector and useDispatch types ?

// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch: () => AppDispatch = useDispatch
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector

Have you try to generate RootState from store.getState ?

export type RootState = ReturnType<typeof store.getState>

CodePudding user response:

When your app is loaded, appState is null. So in this case isAuthenticated property doesn't exist. Therefore, you need to use ? before . to determine null object.

const { LogoutUser } = bindActionCreators(actionCreators, dispatch);
const appState = useSelector((state: RootState) => state.auth);

{appState?.isAuthenticated && (
              <Button
                onClick={handleUserLogout}
                size={'sm'}
                colorScheme={'red'}
              >
                Logout
              </Button>
            )}
  • Related