aboutsummaryrefslogtreecommitdiff
path: root/part1/anecdotes
diff options
context:
space:
mode:
authorIbrahim Mkusa <ibrahimmkusa@gmail.com>2023-04-26 22:24:39 -0400
committerIbrahim Mkusa <ibrahimmkusa@gmail.com>2023-04-26 22:24:39 -0400
commit7a85d56e787f5e90c4c5e08e1ef0d4a7c50d64a7 (patch)
treed7c0d89033f640696f15a81990872ad342690041 /part1/anecdotes
parent5ef2d23f060b99f10138041cf8ac76d955f35903 (diff)
ex 1.13 add vote counter for each anecdotes utilzing arrays in hooks
Diffstat (limited to 'part1/anecdotes')
-rw-r--r--part1/anecdotes/src/App.js16
1 files changed, 10 insertions, 6 deletions
diff --git a/part1/anecdotes/src/App.js b/part1/anecdotes/src/App.js
index 4e33e98..8bc3b2b 100644
--- a/part1/anecdotes/src/App.js
+++ b/part1/anecdotes/src/App.js
@@ -8,12 +8,6 @@ const Button = (props) => {
)
}
-const Display = (props) => {
- return (
- <p>{props.text} {props.count}</p>
- )
-}
-
const App = () => {
const anecdotes = [
'If it hurts, do it more often.',
@@ -28,6 +22,8 @@ const App = () => {
]
const [selected, setSelected] = useState(0)
+ const [votes, setVotes] = useState(Array(anecdotes.length).fill(0))
+
const getRandomInt = (min, max) => {
min = Math.ceil(min)
@@ -35,9 +31,17 @@ const App = () => {
return Math.floor(Math.random() * (max - min) + min)
}
+ const updateVotes = (selected) => {
+ const copy = [...votes]
+ copy[selected] += 1
+ return copy
+ }
+
return (
<div>
<p>{anecdotes[selected]}</p>
+ <p>has {votes[selected]} votes</p>
+ <Button onclick={() => {setVotes(updateVotes(selected))}} text="vote" />
<Button onclick={() => setSelected(getRandomInt(0, anecdotes.length))} text="next anecdote" />
</div>
)