naethan
naethan

Reputation: 23

react redux updating array based on index

I am learning redux using react. I am trying to update an array of numbers based on a button click. I am specifically want to update the counter at specific index based on imported json file.

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { upVote, downVote } from '../store/actions/voteAction';

class Voter extends Component {
    render() {
        const { count, upVote, downVote, id} = this.props
        return (
            <div>
                <button onClick={() => upVote(id)}>+</button>
                The count is {count[id]}
                <button onClick={() => downVote(id)}>-</button>
            </div>
        )
    }
}

const mapDispatchToProps = dispatch => ({
    upVote: (payload) => dispatch(upVote(payload)),
    downVote: (payload) => dispatch(downVote(payload))
  });

const mapStateToProps = (state) => ({
    count: state.vote.count

})
export default connect(mapStateToProps, mapDispatchToProps)(Voter);

I think my issue comes with how i pass and update the payload in my reducer.

import {UP_VOTE,DOWN_VOTE} from '../actions/actionTypes'
import Mice from './../../imports/mice'
const initialState = {
    count: new Array(Mice.length).fill(0)
}


const voteReducer = (state=initialState, action) => {
    const id = action.payload
    switch(action.type){
        case UP_VOTE:
            return{
            ...state, count: state.count[id] + 1
            }
        case DOWN_VOTE:
            return{
            ...state, count: state.count[id] - 1
            }
        default:
            return state
    }

}

export default voteReducer;

I update the array, but every index is still changing and it appears i am still mutating the count array instead of an index inside it.

I have uploaded all my code to CodeSandbox for viewing and experimenting: CodeSandbox Link

Thanks for reading

Upvotes: 1

Views: 780

Answers (1)

Alexander Kireyev
Alexander Kireyev

Reputation: 10825

Use map method to create a new array, add change one element. The Redux switch will be:

switch (action.type) {
  case UP_VOTE:
    return {
      ...state,
      count: state.count.map((vote, i) => (i === id ? vote + 1 : vote))
    };
  case DOWN_VOTE:
    return {
      ...state,
      count: state.count.map((vote, i) => (i === id ? vote - 1 : vote))
    };
  default:
    return state;
}

Working code here https://codesandbox.io/s/74pmomo42j

Upvotes: 1

Related Questions