I have a state with 2 objects (players), of which only 1 can be the player on turn.
How do I save the player on turn into the state, so I can use its data?
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
playerOne: {
name: "foo"
},
playerTwo: {
name: "bar"
}
playerOnTurn: {} // This has to become the same Object as 'playerOne'.
}
}
}
I have tried the following 3 things:
playerOnTurn: this.state.playerOne
Unfortunately it doesn't work, as the state isn't yet defined due to still constructing the state.
2) Writing the same Object twice:
playerOnTurn: { name: "foo" }
It works, but I don't want to write it twice, because a player can contain many properties. It seems like a bad solution in terms maintainability. Because properties could be added/removed later, which could cause them to become nonidentical.
3) Declaring the object before setting it in the state:
class App extends React.Component {
constructor(props) {
super(props);
const playerOne = {
name: "foo"
}
this.state = {
playerOne: playerOne,
playerTwo: {
name: "bar"
}
playerOnTurn: playerOne
}
}
}
It works, but it doesn't seem like a great solution in terms of readability. Because I declare both players in different ways.
Maybe it requires a different approach? E.g. by adding a boolean onTurn
to each player?
Any input/advice is welcome.
You can use a getter function, which allows you to access this
(in context of the object) inside a function:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
playerOne: {
name: "foo"
},,
playerTwo: {
name: "bar"
}
get playerOnTurn() {
return this.playerOne
}
}
}
}
@UniqIdentifierAssignedAtBirth there is?
this
in this context is the object, not the class.It does work,
this
refers to the Object:this.state
in this case. Thank you for the answer, it was exactly what I needed. :)Regardless, you cannot set the player on turn when you need to so it's not practical. More importantly, you can't put getters and setters inside react state objects. stackoverflow.com/questions/50387670/… They will get wiped when you setState
You can't use setters and getters with react state. you have to use
setState
and pure objectsExactly, so what is the point of putting a getter inside a state object?