Home > OS >  display an array with the largest number of votes
display an array with the largest number of votes

Time:10-24

I'm currently having an Introduction to React course on FullStackOpen and I'm stuck in the 1.14 anecdotes exercise, which require the application to display the anecdote with the largest number of votes. The browser is able to render the Mostvote Array, which render the votes of the most voted anecdote, but the most voted (bestAnecdote) anecdote can't be display no matter what I do. Does anyone know where I did wrong? Thank you in advance :) Here below I have attached my React code:

import React, { useState } from 'react'

const Header = (props) => {
  return <h1>{props.contents}</h1>
}

const Button = (props) => (
  <button onClick={props.handleClick}>
    {props.text}
  </button>
) 

const Vote = ({vote}) => (
<p>has {vote} votes</p>
)

const App = () => {

  const contents = {
      text1: "Anecdote of the day",
      text2: "Anecdote with most votes"
  }

  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 random = () => (
    Math.floor(Math.random() * 7)
  )

  const [selected, setSelected] = useState(0)
  const [vote, setVote] = useState(new Array(anecdotes.length).fill(0))

  const Anecdotevoting = () => {
    const copy = [...vote];
      copy[selected]  = 1;
      setVote(copy);
  }
  
  const Mostvote = () => (
    <p>has {Math.max(...vote)} votes</p>
  )

  const bestAnecdote = anecdotes[vote.indexOf(Mostvote)];
  
  console.log(bestAnecdote)
  return (
    <div>
      <Header contents = {contents.text1}/>
      {anecdotes[selected]}<br/>
      <Vote vote = {vote[selected]}></Vote>
      <Button handleClick={Anecdotevoting} text = 'vote'/>
      <Button handleClick={() => setSelected(random)} text = 'next anecdote'/>
      <Header contents = {contents.text2}/>
      <bestAnecdote anecdotes = {anecdotes[vote.indexOf(Mostvote)]}/>
      <Mostvote vote = {Mostvote}/>
    </div>
  )
}

export default App

CodePudding user response:

Nick hit most of what the issues are. Here is a working version you can use to see where the issues are:

import React, { useState } from 'react'

const Header = (props) => {
  return <h1>{props.contents}</h1>
}

const Button = (props) => (
  <button onClick={props.handleClick}>
    {props.text}
  </button>
) 

const Vote = ({vote}) => (
<p>has {vote} votes</p>
)

const BestAnecdote = (props) => {
  return <h4>{props.anecdotes}</h4>
}

const App = () => {

  const contents = {
      text1: "Anecdote of the day",
      text2: "Anecdote with most votes"
  }

  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 random = () => (
    Math.floor(Math.random() * 7)
  )

  const [selected, setSelected] = useState(0)
  const [vote, setVote] = useState(new Array(anecdotes.length).fill(0))

  const Anecdotevoting = () => {
    const copy = [...vote];
      copy[selected]  = 1;
      setVote(copy);
  }
  
  const Mostvote = () => (
    <p>has {Math.max(...vote)} votes</p>
  )
  
  return (
    <div>
      <Header contents = {contents.text1}/>
      {anecdotes[selected]}<br/>
      <Vote vote = {vote[selected]}></Vote>
      <Button handleClick={Anecdotevoting} text = 'vote'/>
      <Button handleClick={() => setSelected(random)} text = 'next anecdote'/>
      <Header contents = {contents.text2}/>
      <BestAnecdote anecdotes = {anecdotes[vote.indexOf(Math.max(...vote))]}/>
      <Mostvote vote = {Mostvote}/>
    </div>
  )
}

export default App

CodePudding user response:

Issues

  1. You are mutating the state in Anecdotevoting with copy[selected] = 1;. Even though you shallow copied the vote state, the elements still refer back to the elements of the original.
  2. The MostVote value is JSX, so anecdotes[vote.indexOf(Mostvote)]; will always be -1.

Solution

Update the anecdoteVoting handler to not mutate the state. You can map the previous state to the next, and when the mapped index matches the selected return a new value, otherwise return the current value.

const anecdoteVoting = () => {
  setVote((votes) => votes.map((vote, i) => vote   (i === selected ? 1 : 0)));
};

Compute a mostVotes and index at the same time.

const { mostVotes, index } = vote.reduce(
  (mostVotes, curr, index) => {
    if (curr > mostVotes.mostVotes) {
      return { mostVotes: curr, index };
    }
    return mostVotes;
  },
  { mostVotes: Number.NEGATIVE_INFINITY, index: -1 }
);

...

<BestAnecdote anecdote={anecdotes[index]} />
<Vote vote={mostVotes} />

Edit display-an-array-with-the-largest-number-of-votes

Full code:

import React, { useState } from "react";

const Header = (props) => {
  return <h1>{props.contents}</h1>;
};

const Button = (props) => (
  <button onClick={props.handleClick}>{props.text}</button>
);

const Vote = ({ vote }) => <p>has {vote} votes</p>;

const BestAnecdote = ({ anecdote }) => <p>{anecdote}</p>;

const contents = {
  text1: "Anecdote of the day",
  text2: "Anecdote with most votes"
};

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 random = () => Math.floor(Math.random() * anecdotes.length);

const App = () => {
  const [selected, setSelected] = useState(0);
  const [vote, setVote] = useState(new Array(anecdotes.length).fill(0));

  const anecdoteVoting = () => {
    setVote((votes) => votes.map((vote, i) => vote   (i === selected ? 1 : 0)));
  };

  const { mostVotes, index } = vote.reduce(
    (mostVotes, curr, index) => {
      if (curr > mostVotes.mostVotes) {
        return { mostVotes: curr, index };
      }
      return mostVotes;
    },
    { mostVotes: Number.NEGATIVE_INFINITY, index: -1 }
  );

  return (
    <div>
      <Header contents={contents.text1} />
      {anecdotes[selected]}
      <br />
      <Vote vote={vote[selected]}></Vote>
      <Button handleClick={anecdoteVoting} text="vote" />
      <Button handleClick={() => setSelected(random)} text="next anecdote" />
      <Header contents={contents.text2} />
      <BestAnecdote anecdote={anecdotes[index]} />
      <Vote vote={mostVotes} />
    </div>
  );
};
  • Related