JavaScript React Basics (retired) Designing Data Flow Adding Players to the Scoreboard

Rohit Thorat
Rohit Thorat
12,191 Points

how to implement nextId in this code

Application.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Header from './Header';
import Player from './Player';
import AddPlayerForm from './AddPlayerForm';
import './App.css';



class Application extends Component {

  constructor(props){
    super(props);

    this.state = {
      playerState: this.props.initialPlayers
    };
  }

onScoreChangeApp(index,delta) {
   // console.log("onScoreChangeApp",index,delta);
   this.state.playerState[index].score += delta;
   this.setState(this.state);
}

onPlayerAdd(name) {
  console.log("name added",name);
  this.state.playerState.push({
    name: name,
    score: 0,
    id: 4,
  });
  this.setState(this.state);

}

render(){

    return(
      <div className="scoreboard">
         <Header titleHeader={this.props.titleApp} playerHead={this.props.initialPlayers}/>
           <div className="players">

             {this.state.playerState.map(function(p,index) {
              return (
              <Player onScoreChange={function(delta) {this.onScoreChangeApp(index,delta)}.bind(this)}
                      name={p.name}
                      scoreP={p.score}
                      key={p.id} />
              );
            }.bind(this))}

          </div>
          <AddPlayerForm onAdd={this.onPlayerAdd.bind(this)}/>
      </div>
    );
    }
  }
  Application.propTypes = {
    titleApp: PropTypes.string,
    initialPlayers: PropTypes.arrayOf(
      PropTypes.shape({
                        name: PropTypes.string.isRequired,
                        score: PropTypes.number.isRequired,
                        id: PropTypes.number.isRequired
                     })).isRequired

  };
  Application.defaultProps = {
    titleApp: "Scoreboard",

  };


export default Application;
Rohit Thorat
Rohit Thorat
12,191 Points

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import './App.css';
import Application from './Application';
import registerServiceWorker from './registerServiceWorker';

var PLAYERS = [
  {
    name: "Rohit Thorat",
    score: 77,
    id: 1
  },
  {
    name: "Son Goku",
    score: 95,
    id: 2
  },
  {
    name: "Prince Vegeta",
    score: 56,
    id: 3
  }
]


ReactDOM.render(<Application initialPlayers={PLAYERS}/>, document.getElementById('root'));
registerServiceWorker();
Rohit Thorat
Rohit Thorat
12,191 Points

i am pushing a new player in the array using onPlayerAdd method . Here my id value is hard coded i.e.

this.state.playerState.push({
    name: name,
    score: 0,
    id: 4,
  });

i want to use

var nextId = 4 

and replace it in the code like

id: nextId 

and then increase nextId by 1 , i tried using this -

onPlayerAdd(name) {
var nextId = 4;
  console.log("name added",name);
  this.state.playerState.push({
    name: name,
    score: 0,
    id: nextId,
  });
  this.setState(this.state);
nextId += 1;
}

but it is not increasing the value of nextId

2 Answers

Rohit, try adding a state variable nextId in your component Constructor, right below playerState. Give it an initial value.

Then use it and increment it in your onPlayerAdd function:

  this.state.playerState.push({
    name: name,
    score: 0,
    id: this.state.nextId,
  });
  this.setState((prevState) => {
    return {nextId: prevState.nextId++};
  });

ref: react docs

Mike Jensen
Mike Jensen
11,718 Points

You might consider using shortid. It's an npm library which "creates amazingly short non-sequential url-friendly unique ids".

You just need to:

  1. install it: npm install shortid
  2. import it: import shortid from 'shortid
  3. use it: id: shortid.generate()