Search code examples
reactjsreduxreact-redux

useSelector doesn't work in react redux app


I am creating a counter application using react and redux.

In the counterSlice.js file, I included this line: export const selectCount = (state) => state.count;

And in the Counter.js file, I have included these lines:

import { changeValueBy, selectCount } from "./counterSlice";

const count = useSelector(selectCount);

But the value of count remains undefined. My complete code is here. Please tell me what I'm doing wrong.


Solution

  • You missed out to create a store and wrap the app with its Provider as following:

    import { Counter } from "./features/counter/Counter";
    import { Provider } from "react-redux";
    import { createStore } from "redux";
    import counter from "./features/counter/counterSlice";
    
    const store = createStore(counter);
    
    function App() {
      return (
        <Provider store={store}>
           <Counter />
        </Provider>
      );
    }
    
    export default App;
    
    

    BTW, I fixed your codesanbox here