useSelector (from Redux +React) returns undefined

58 Views Asked by At

I am using React + TypeScript for development and using Redux for centralised state management - to store the current user logged in.

Here is the userReducer:

Here is the store:

Here is the snippet of code inside my React component, where I try to access the user state:

I'm not sure why useSelector returned undefined since I have defined an initialState in the userReducer.

1

There are 1 best solutions below

2
markerikson On BEST ANSWER

Because you defined the root state as {user}. In other words, the userReducer's data is attached to the root state as state.user.

So, your selector needs to be state => state.user.

You also have a problem in your store file. You've created another reducer function with const rootReducer = combineReducers({userReducer}), and then inferred the RootState type from that.

That is wrong in two ways:

  • That reducer function is not being used at all! configureStore already made its own root reducer function from the definition you provided and is using that
  • Your RootState type is wrong, because it's being inferred from the wrong function

That's why you're not even getting a TS error here.

Instead, you need to delete the combineReducers line, and then do:

type RootState = ReturnType<typeof store.getState>

per our TS usage docs: