Why does 'React App' button (that activates useState function) crashes after some uses?

Viewed 21

I was working in an exercise from Full Stack Open. The task was to create a button that displays a random "anecdote" from an array full of strings that they give you. The exercise gets more complicated, they ask you to create an array with votes for each "anecdote" (which I called "initialVotes"), and have a button that adds a vote (they also ask you to display the one with the highest value).

Now, I'm giving every detail of the exercise as I didn't realize it could crash after I finished everything. The issue is weird, everything "works fine", until you click the "next anecdote" button a few times, then it stops working (the amount of times you can use it before it crashes changes everytime you reload the page, which makes it even weirder imo). If you use the "add vote" button, it MIGHT work again (can't even think why).

This is the code:

import { useState } from 'react'
import React from 'react'

const firstIndex = Math.floor(Math.random() * 7)

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(firstIndex)

  const newIndex = Math.floor(Math.random() * 7)

  // We could use: const initialVotes(Uint8Array)
  const n = 7  // arbitrary length
  const initialVotes = Array(n).fill(0)

  const [votes, setVotes] = useState(initialVotes)

  const addVote = (index) => {
    const vote = votes[index] + 1
    setVotes([
      ...votes.slice(0, index),
      vote,
      ...votes.slice(index + 1, n)
    ])
  }

  const mostVotes = Math.max(...votes);
  const mvIndex = votes.indexOf(mostVotes)

  console.log(newIndex)
  console.log(anecdotes[selected])

  return (
    <React.Fragment>
      <h1>Anecdote of the day</h1>
      <h4>{anecdotes[selected]}</h4>
      <p>has {votes[selected]} votes</p>
      <button type="button" onClick={() => addVote(selected)}>vote</button>
      <button type="button" onClick={() => setSelected(newIndex)}>next anecdote</button>
      <h1>Anecdote with most votes</h1>
      <p>The anecdote with most votes is: <mark>{anecdotes[mvIndex]}</mark></p>
      <p>With "{mostVotes}" votes</p>
    </React.Fragment>
  )
}

export default App
1 Answers

When the newIndex is the same as the current selected state, doing setSelected(newIndex) will cause the component to fail to re-render. The new value for selected should be something other than the current value in state for the state setter to work.

One approach for this is:

let newIndex;
do {
  newIndex = Math.floor(Math.random() * 7);
} while (newIndex === selected);

const { useState } = React;
const firstIndex = Math.floor(Math.random() * 7)

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(firstIndex)

  let newIndex;
  do {
    newIndex = Math.floor(Math.random() * 7);
  } while (newIndex === selected);

  // We could use: const initialVotes(Uint8Array)
  const n = 7  // arbitrary length
  const initialVotes = Array(n).fill(0)

  const [votes, setVotes] = useState(initialVotes)

  const addVote = (index) => {
    const vote = votes[index] + 1
    setVotes([
      ...votes.slice(0, index),
      vote,
      ...votes.slice(index + 1, n)
    ])
  }

  const mostVotes = Math.max(...votes);
  const mvIndex = votes.indexOf(mostVotes)

  return (
    <React.Fragment>
      <h1>Anecdote of the day</h1>
      <h4>{anecdotes[selected]}</h4>
      <p>has {votes[selected]} votes</p>
      <button type="button" onClick={() => addVote(selected)}>vote</button>
      <button type="button" onClick={() => setSelected(newIndex)}>next anecdote</button>
      <h1>Anecdote with most votes</h1>
      <p>The anecdote with most votes is: <mark>{anecdotes[mvIndex]}</mark></p>
      <p>With "{mostVotes}" votes</p>
    </React.Fragment>
  )
}


ReactDOM.createRoot(document.querySelector('.react')).render(<App />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div class='react'></div>

Or you could generate a random number from 0 to 5 instead of 0 to 6, and if the generated number is equal to the current selected, assign 6 to newIndex.

Related