Home > Software engineering >  dynamic function/state calls fail to be inline
dynamic function/state calls fail to be inline

Time:09-28

i have a bunch of states:

const [player1,setPlayer1] = useState()
const [player2,setPlayer2] = useState()
const [player3,setPlayer3] = useState()
const [player4,setPlayer4] = useState()

which I need to call the setplayer4 if the position that I select is 4 for example so.

if (position===4){
setPlayer`${position}(something)

which doesnt work, what would work?

CodePudding user response:

You cannot dynamically construct variable names in Javascript. You can do the following instead

  1. Use array indices to determine which setter to use
const [player1,setPlayer1] = useState()
const [player2,setPlayer2] = useState()
const [player3,setPlayer3] = useState()
const [player4,setPlayer4] = useState()

const setPlayers = [setPlayer1, setPlayer2, setPlayer3, setPlayer4]


// In your handler
if (position === 4) {
  setPlayers[position - 1](something)
}
  1. Use objects so that you use dynamic keys
const [player1,setPlayer1] = useState()
const [player2,setPlayer2] = useState()
const [player3,setPlayer3] = useState()
const [player4,setPlayer4] = useState()

const setPlayers = {
  player1: setPlayer1, 
  player2: setPlayer2, 
  player3: setPlayer3, 
  player4: setPlayer4
}


// In your handler
if (position === 4) {
  setPlayers[`player${position}`](something)
}
  1. If state is related, tie it together in a single object
// Use arrays if you have non-deterministic number of players
const [players, setPlayers] = {
  player1: null,
  player2: null,
  player3: null,
  player4: null,
}

// In your handler
if (position === 4) {
  setPlayers({
    ...players,
    player4: something
  });
}

CodePudding user response:

Do it with if statements, or with switch:

   if(position===1){
      setPlayer1("something")
   }
  if(position===2){
    setPlayer2("something")
  }
  ...etc
  • Related