Home > Back-end >  My react app is not re-rendering on Redux's store update
My react app is not re-rendering on Redux's store update

Time:12-17

I am learning Redux, in this app I am using react-redux and redux, I am not mutating the store's state, but still my app is not re-rendering

I have this basic counter app, you press the button the number increases, you press the - button it decreases

My code:

app.js : `

import './App.css';
import { useDispatch } from 'react-redux';
import { store } from './store';

function App() {
  const dispatch = useDispatch();
  const handleIncrease = () => {
    console.log(" ");
    dispatch({
      type : 'aumentar'
    })
    console.log(store.getState());
  }
  const handleDecrease = () => {
    console.log("-");
    dispatch({
      type : 'restar'
    })
  }
  return (
    <div className="App">
      <h1>Contador</h1>
      <h3>{store.getState()}</h3>
      <button onClick={handleIncrease}> </button>
      <button onClick={handleDecrease}>-</button>
    </div>
  );
}

export default App;

`

index.js : `

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { Provider } from 'react-redux';
import { store } from './store';

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

`

store.js `

import { legacy_createStore as createStore } from "redux";

let initialState = 0;

const reducer = (state = initialState, action) => {
    switch(action.type){
        case 'aumentar' :
            return state   1;
        case 'restar' :
            return state - 1;
        default :
            return state;
    }
}

export const store = createStore(reducer);

`

CodePudding user response:

You need to use useSelector to access entries from the state:

// 1. import the hook
import { useDispatch, useSelector } from 'react-redux';
import { store } from './store';

function App() {
  const dispatch = useDispatch();
  // 2. use it to extract what you need
  const count = useSelector(state => state);
  const handleIncrease = () => {
    console.log(" ");
    dispatch({
      type : 'aumentar'
    })
  }
  const handleDecrease = () => {
    console.log("-");
    dispatch({
      type : 'restar'
    })
  }

  // 3. use the extracted variable inside JSX
  return (
    <div className="App">
      <h1>Contador</h1>
      <h3>{count}</h3>
      <button onClick={handleIncrease}> </button>
      <button onClick={handleDecrease}>-</button>
    </div>
  );
}

When your state will become more complex / you will use more reducers, your code will look like:

const whatYouNeed = useSelector(state => state.reducerName.something);
  • Related