I am really stuck on this one. This is a vote application, using React redux. When I click a button the state is changed and the amount of votes is correctly displayed in the console. The reducer is also working. However the amount of votes is not refreshed on the page. All votes on the webpage stay at zero.
This is the app:
import { useSelector, useDispatch } from 'react-redux'
import { createStore } from 'redux'
import reducer from './reducers/anecdoteReducer'
const store = createStore(reducer)
const App = () => {
//const dispatch = useDispatch()
const anecdotes = useSelector(state => state)
console.log('Anecdotes!',anecdotes)
const vote = (id) => {
console.log('vote', id)
store.dispatch({
type: 'VOTE',
payload: {
id: id
}
})
}
return (
<div>
<h2>Anecdotes</h2>
{anecdotes.map(anecdote =>
<div key={anecdote.id}>
<div>
{anecdote.content}
</div>
<div>
has {anecdote.votes}
<button onClick={() => vote(anecdote.id)}>vote</button>
</div>
</div>
)}
<h2>create new</h2>
<form>
<div><input /></div>
<button>create</button>
</form>
</div>
)
}
export default App
And this is the reducer:
const anecdotesAtStart = [
'First anecdote',
'Second anecdote'
]
const getId = () => (100000 * Math.random()).toFixed(0)
const asObject = (anecdote) => {
return {
content: anecdote,
id: getId(),
votes: 0
}
}
const initialState = anecdotesAtStart.map(asObject)
const reducer = (state = initialState, action) => {
console.log('state now: ', state)
console.log('action', action)
switch(action.type) {
case 'VOTE': {
const id = action.payload.id
const anecdoteToChange = state.find(n => n.id === id)
const changedAnecdote = {
...anecdoteToChange,
votes:anecdoteToChange.votes+=1
}
return state.map(anecdote =>
anecdote.id !== id ? anecdote : changedAnecdote
)}
default:
return state
}
}
export default reducer