Search code examples
javascriptreactjsredux

Redux Updating Objects State


counterReducer; I am trying to increase the counters state(object) whenever the button is pressed. But not exactly sure how to update the objects state by 1 (increment) and -1(decrement). enter image description here Every time I click the + button and update objects state with state+ 1 I get this above ^

const initialState = {
    counter: 0

}

const counter = (state=initialState,action) => {
    switch(action.type){
        case 'INCREMENT':
            return {...state,counter : state +1}
        case 'DECREMENT':
            return {...state,counter : state -1}
        default:
            return state;  state
    }
}

export default counter; 

app./js

import React from 'react';
import {useSelector,useDispatch} from 'react-redux';
import  { decrement, increment} from './Actions/counterAction'

function App() {
  const counter = useSelector(state => state.counter) // pull out counters state which is zerp
  const dispatch = useDispatch();
  return (
    <div className="App">
      <h1> counter {counter}</h1>
      <button onClick ={() => dispatch(increment())}> + </button> 
      <button onClick ={() => dispatch(decrement())}> - </button> 
    </div>
  );
}

export default App;

Action

export const increment = (x) => {
    return{
        type : 'INCREMENT',

    }
}
export const decrement = (x) => {
    return{
        type : 'DECREMENT',

    }
}

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { createStore } from 'redux';
import counter from './Reducers/counterReducer';
import { Provider } from 'react-redux'//make global  


const myStore = createStore(counter)

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

Solution

  • In

    case 'INCREMENT':
                return {...state,counter : state +1}
            case 'DECREMENT':
                return {...state,counter : state -1}
    

    Try

    case 'INCREMENT':
                return {...state, counter : counter + 1 }
            case 'DECREMENT':
                return {...state, counter : counter - 1 }