Search code examples
javascriptreactjsreact-reduxmernredux-toolkit

Redux toolkit. Uncaught Error: uSES not initialized


I'm learning about the react-redux toolkit and here is some problem I'm facing I just simply want to increment and decrement numbers by clicking on buttons.

File no.1(counterReducer.js)

import {createSlice } from '@reduxjs/toolkit'
export const counter = createSlice({
    name:'counter',
    initialState:{
        value:0
    },
    reducers:{
        increment:(state)=>{
            state.value += 1
        },
        decrement:(state)=>{
            state.value -= 1
        },
        incrementByAmount:(state,action)=>{
            state.value += action.payload
        }
    }
})
export const { increment, decrement, incrementByAmount} = counter.actions
export default counter.reducer

File no.2(store.js)

import { configureStore } from "@reduxjs/toolkit";
import counterReducers from "./counterReducers";

export default configureStore({
    reducer:{
        counter: counterReducers
    }
}) 

File no.3(index.js)

import { Provider } from 'react-redux/es/exports';
import store from './state/store';


const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Provider store={store}>
    <App />
    </Provider>
  </React.StrictMode>
);

File no.4(Home.js)

in this file I'm trying to use state.

import { useSelector, useDispatch } from "react-redux/es/exports";
import { increment } from "../state/counterReducers";
const Home = () => {
  const counter = useSelector((state) => state.counter);
  const dispatch = useDispatch();
  return (
    <>
      <li>
        <a href="/" className="px-2 py-1 bg-cyan-500">Your balance:{counter}</a></li>
      <button className="ml-2 m-1 px-3 bg-orange-500"
        onClick={() => {dispatch(increment())}}>+</button>
    </>
  );
};

export default Home;

And This is the image of error. the image of error.


Solution

  • Your problem seems to be in your useSelector, you aren't accessing the state at all, just try to use state.counter.value instead of state.counter.

    const Home = () => {
    
      // change to state.counter.value, so you get the state value
      const counter = useSelector((state) => state.counter.value);
      const dispatch = useDispatch();
      return (
        <>
          <li>
            <a href="/" className="px-2 py-1 bg-cyan-500">Your balance:{counter}</a></li>
          <button className="ml-2 m-1 px-3 bg-orange-500"
            onClick={() => {dispatch(increment())}}>+</button>
        </>
      );
    };
    export default Home;