0

I am learning redux and I am not able to get the counter to work. I have action.js, reducer.js, and store.js set up and in the index.js, I created a store and a provider. I am also using react-redux for useSelector and useDispatch in the App.js I don't know what am I missing here.

The counter doesn't seem to be increased when click in the App.js. What am I missing here?

Thanks a lot and in advance:

//Reducer.js

const counterReducer = (state = 0,action) => {
    switch(action.type){
        case "INCREMENT":
            return state + action.payload
        case "DECREMENT":
            return state - action.payload
        default:
            return state
    }
}

export default counterReducer


//Action.js

const increment = (steps) => {
    return {
        type: 'INCREMENT',
        payload: steps
    }
}

const decrement = (steps) => {
    return {
        type: 'DECREMENT',
        payload: steps
    }
}


//store.js

import {createStore} from 'redux'
import counterReducer from './reducer'

const myStore = createStore(counterReducer)

export default myStore


//index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import {Provider} from 'react-redux'
import myStore from './store'

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


serviceWorker.unregister();


//App.js

import React from 'react';
import './App.css';
import {useSelector, useDispatch} from 'react-redux'
import {increment,decrement} from './action'

function App() {
  const counter = useSelector(state => state.counterReducer)
  const dispatch = useDispatch()
  console.log(counter)
  return (
    <div className="App">
       <h1>Counter {counter}</h1>
       <button onClick={() => dispatch(increment(2))}>+</button>
       <button onClick={() => dispatch(decrement(2))}>-</button>
    </div>
  );
}

export default App;
Nat
  • 679
  • 1
  • 9
  • 24

1 Answers1

1

Very small mistake.

You are not using combineReducers. So,there is no need to refer reducer's name to access its state in store.

In useSelector, it should be

  const counter = useSelector(state => state);

instead

  const counter = useSelector(state => state.counterReducer)
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
  • I see and thanks. I have changed to state => state, but my button seems to complain about App.js:12 Uncaught TypeError: Object(...) is not a function which is the button onClick. I don't see any syntax error in the button click event. – Nat Jun 29 '20 at 06:19
  • In your action, are you exporting action function increment and decrement? – RIYAJ KHAN Jun 29 '20 at 06:22
  • I have something new today and that is use combine reducer when you have 2 or more reducers else just use state. Thanks, guys – Nat Jun 29 '20 at 06:30