This is my first time making a finite state Automata. I tried making a stop light kind of program where if you click the button, the light changes once, starting at green, then to yellow if clicked again, then to red, before looping again. I managed to make it work, except for one small bug. It needs to be clicked twice before the screen updates, and I don't really know how to fix it.
I noticed on my console that the currentLightState changes when I click on it, but reverts back to the previous color on the first click. I figured out that it's because it is not in sync with my state. However, when I attempt to put currentLightState inside the class, and assign this.state.light, currentLightState becomes undefined. I tried adding a .bind(this) at the end of this.state.light, but I just get another error saying it's not a function. Any suggestions?
I didn't post my update function or my onHandleClick function since it doesn't directly deal with currentLightState.
const lightMachine = {
green:{
LIGHT: 'yellow'
},
yellow:{
LIGHT: 'red'
},
red:{
LIGHT: 'green'
}
}
// current location of currentLightState
let currentLightState = 'green';
class App extends React.Component{
constructor(props){
super(props);
this.state = {
light: 'green' //initial value
};
}
transition(state, action){
// This is where my currentLightState messes up the first run
currentLightState = this.state.light
const nextLightState = lightMachine[currentLightState][action]
this.setState({light: nextLightState})
}
render(){
return(
<div>
<button onClick={this.onHandleClick.bind(this)}>
change the Light!
</button>
{currentLightState}
</div>
);
}
}
EDIT: Here is my onHandleClick function :)
onHandleClick(){
this.update(currentLightState)
};
also, I think I solved my problem by just substituting the currentLightState in the render function with this.state.light .
Idk if that is a legitimate fix or not, but it seems to work currently.
it would be nice though if someone can still answer why when you put the currentLightState inside the class, and assign state.light to it, it becomes undefined. It would help expand my React knowledge :)