Show initial state in redux?

I have a simple redux/react app. It works fine except it doesn't show the initial state (the users scores). Grateful for any help! The reducer is below:

  const initialState = [{userScore: 0, computerScore :0}];
 const dataReducer = (state = initialState, action) => {
 switch (action.type) {
  case 'USER_WINS':
  return [
    {
      userScore: state.userScore + 1,
      computerScore: state.computerScore

    }
  ]
  case 'COMPUTER_WINS':
    return [
      {
        userScore: state.userScore,
        computerScore: state.computerScore +1
      }
    ]
default:
  return state
}
}

And the main class is below:

    class Interface extends Component{
  constructor(props) {
  super(props);
  this.computerChoice = this.computerChoice.bind(this);
  this.userChoice = this.userChoice.bind(this);
}

computerChoice () {
  var choicesArray = ['Paper','Rock','Scissors'];
  var computerResponse = choicesArray[Math.floor(Math.random() * 3)];
   return computerResponse;
}

userChoice (userInput){
    var computerInput = this.computerChoice();
    if (
        (userInput === 'Rock' && computerInput === 'Scissors')||
        (userInput === 'Paper' && computerInput === 'Rock') ||
        (userInput === 'Scissors' && computerInput === 'Paper')
    ) {
         this.props.userWinsGame();
    } else {

    }
  }
  render() {
  const value  = this.props;
    return (
      <div>

This is where I want to display the scores:

         Human: {value.userScore}
         Computer: {value.computerScore}
      <br/>
       <button value='Rock' onClick={(e) => this.userChoice(e.target.value)} >Rock</button>
      <button value='Paper' onClick={(e) =>this.userChoice(e.target.value)} >Paper</button>
      <button value='Scissors' onClick={(e) =>this.userChoice(e.target.value)} >Scissors</button>
      </div>
      )
     }
 }

Everything is dispatched here:

    const render = () => ReactDOM.render(
<Interface
  value={store.getState()}
    userWinsGame = {() => store.dispatch({ type: 'USER_WINS' })}
    computerWinsGame = { () => store.dispatch({ type: 'COMPUTER_WINS' 
})}
 />,
root

)

Grateful for your help- everything works but displaying the initial state!

1 answer

  • answered 2017-11-12 20:11 Konrad D

    The main question would be, why is your initialState an array? Why your state is an array at all? I think you should consider to keep it as an object.

    Anyways - while your initialState is an array:

    const initialState = [{userScore: 0, computerScore :0}],

    you are trying to set a value of key as if the state would be an object.

    userScore: state.userScore + 1,

    state.userScore will return undefined, plus adding 1 to it, will throw NaN.

    So as I stated above I would strongly suggest you to use an object as your state. However, if you really want it to be an array, use a proper notation then:

    userScore: state[0].userScore + 1,