Home > OS >  React ui not updating although i'm changing the state
React ui not updating although i'm changing the state

Time:11-25

import React, { useState } from "react";

const App = () => {
  const anecdotes = [
    "If it hurts, do it more often",
    "Adding manpower to a late software project makes it later!",
    "The first 90 percent of the code accounts for the first 10 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.",
    "Any fool can write code that a computer can understand. Good programmers write code that humans can understand.",
    "Premature optimization is the root of all evil.",
    "Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it.",
    "Programming without an extremely heavy use of console.log is same as if a doctor would refuse to use x-rays or blood tests when diagnosing patients",
  ];

  const [selected, setSelected] = useState(0);
  const [votes, setVotes] = useState([0, 0, 0, 0, 0, 0, 0]);

  function getRandomInt(max) {
    return Math.floor(Math.random() * max);
  }

  function pickRandomNumber() {
    setSelected(getRandomInt(anecdotes.length));
  }

  function addVote() {
    const newVotes = votes;
    newVotes[selected]  = 1;
    setSelected(selected);
    setVotes(newVotes);
  }

  return (
    <div>
      <div>{anecdotes[selected]}</div>
      <div>Has {votes[selected]} votes </div>
      <button onClick={addVote}>vote</button>
      <button onClick={pickRandomNumber}>next anecdote</button>
    </div>
  );
};

export default App;

So I basically have 7 anecdotes and i'm trying when i press on the button vote , it should add a vote , i'm counting that by having the array votes and adding one to the index in the votes array , the number gets added by the addVote function but it doesn't update on the screen , if i were to skip through to the same anecdote again , it shows just fine , any idea ?

this is the related div that doesn't update

  <div>Has {votes[selected]} votes </div>

CodePudding user response:

Issue

The issue here is one of state mutation. You are mutating a reference to the current state and then saving it back into state. The state reference never changes so React doesn't "see" that anything was update and doesn't trigger a rerender.

function addVote() {
  const newVotes = votes;  // <-- reference to state
  newVotes[selected]  = 1; // <-- state mutation!!
  setSelected(selected);
  setVotes(newVotes);      // <-- reference saved back into state
}

Solution

To resolve you necessarily need to create a new state reference. Remember that arrays are copy by reference as well, so array elements need to be new references. Also, any time you are incrementing counts or the next state value depends on any previous state value you should use a functional state update to correctly update from the previous state.

function addVote() {
  setSelected(selected);
  setVotes(votes => votes.map((vote, i) => i === selected ? vote   1 : vote);
}

CodePudding user response:

This should fix it:

function addVote() {
    const newVotes = [...votes];
    newVotes[selected]  = 1;
    setSelected(selected);
    setVotes(newVotes);
  }

You can read this answer for further explanation!

  • Related