Files
fullstackopen/part1/1.12-1.14-anecdotes/src/App.js
T

61 lines
2.0 KiB
JavaScript
Raw Normal View History

2021-08-26 20:55:18 +07:00
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 90 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)
2021-08-26 21:11:03 +07:00
const [points, setPoints] = useState(Array(anecdotes.length).fill(0))
2021-08-26 22:18:40 +07:00
console.log(points)
2021-08-26 20:55:18 +07:00
const setRandom = () => {
const min = 0
const max = anecdotes.length-1
const random = Math.floor(Math.random() * (max-min+1)) + min
2021-08-26 22:18:40 +07:00
//console.log(random)
2021-08-26 20:55:18 +07:00
setSelected(random)
}
2021-08-26 21:11:03 +07:00
const setVote = () => {
2021-08-26 22:18:40 +07:00
const newpoints = [...points]
2021-08-26 21:11:03 +07:00
newpoints[selected] += 1
setPoints(newpoints)
}
2021-08-26 22:23:26 +07:00
const BestNote = (props) => {
2021-08-26 22:18:40 +07:00
const best = props.data
const mostvote = Math.max(...best)
const index = best.indexOf(mostvote);
2021-08-26 22:23:26 +07:00
2021-08-26 22:18:40 +07:00
return (
<div>
<h2>Anecdote with most votes</h2>
2021-08-26 22:23:26 +07:00
{mostvote >0 && <div><p>{props.notes[index]}</p>
<span>has {mostvote} votes</span></div>}
2021-08-26 22:18:40 +07:00
</div>
)
}
2021-08-26 20:55:18 +07:00
return (
<div>
2021-08-26 22:18:40 +07:00
<div>
<h1>Anecdote of the day</h1>
<p>{anecdotes[selected]}</p>
<p>has {points[selected]} votes</p>
<button onClick={setVote}>vote</button><button onClick={setRandom}>Next Anecdote</button>
</div>
2021-08-26 22:23:26 +07:00
<BestNote data={points} notes={anecdotes}/>
2021-08-26 22:18:40 +07:00
2021-08-26 20:55:18 +07:00
</div>
)
}
export default App