Reputation: 3488
I'm trying to setup a redux environment and I'm stumped as to why I am having this behavior.
I have my root state here on my reducer:
export type RootState = {
counter: number;
};
const initialState: RootState = { counter: 0 };
const staticLesson = (state = initialState, action: any) => {
switch (action.type) {
case "INCREMENT":
return state.counter + 1;
default:
return state;
}
};
export default staticLesson;
I then combine it here:
import staticLesson from "./staticLesson/index";
import { combineReducers } from "redux";
const rootReducer = combineReducers({
staticLesson,
});
export default rootReducer;
I wrap my App with the Provider:
import { createStore } from "redux";
import rootReducer from "./redux/reducers";
import { Provider } from "react-redux";
import { composeWithDevTools } from "redux-devtools-extension";
const store = createStore(rootReducer, composeWithDevTools());
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById("root")
);
Yet, when I try to log it in my component, the value is undefined.
const Component = () => {
const staticLesson = useSelector((state: RootState) => state);
const dispatch = useDispatch();
console.log("counter", staticLesson.counter); <-- logs undefined
return (
...
)
}
What I don't understand is why if I just log staticLesson
, it appears as expected in my console. But if I try to access the value on the object, instead of getting the value 0
for my counter ... I get undefined
. staticLesson
is showing up in my devTools, it's there ... I'm stumped, what am i messing up?
Upvotes: 0
Views: 421
Reputation: 9063
I'm pretty sure you should be returning the staticLesson
property from the state in your useSelector
call. In useSelector
you're returning the entire state. So it should be:
const staticLesson = useSelector((state: RootState) => state.staticLesson);
Upvotes: 1