0

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?

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Sweet, thanks that did it. Such a small little thing to miss

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.