I am experimenting with js + React and I am facing an unexpected behavior:
In the following example, while it seems to work fine at first I do not get a score change when (this.state.progress.length%3==0)
as expected.
The progress string seems to be updating nicely but the score updates every fourth click...
Edit: I should pin-point the source of the issue because ppl are busy, the problem is the way the handleClick()
on the child component interacts (calls) the scoreUpdate()
from the same component. However I do not think the solution is trivial because the consol.log() example at the end of the question works.
There is obviously an issue on the way I am organizing my code, but what?
Should I be using Promises to call my scoreUpdate()
function?
Or is there a better way to go around this?
Child component:
import React from 'react';
export class Child extends React.Component {
constructor(props) {
super(props);
this.state = { progress: "0",
score: 0};
this.handleClick = this.handleClick.bind(this);
this.scoreUpdate = this.scoreUpdate.bind(this);
}
handleClick(e) {
let previous = this.state.progress;
let score = Number(e.currentTarget.id);
this.setState({progress: previous+e.currentTarget.id});
this.scoreUpdate(score);
}
scoreUpdate(score) {
if (this.state.progress.length%3==0) {
let previous = this.state.score;
this.setState({score: previous+score}); }
}
render() {
return (
<div>
<ul>
<li id="1" onClick={this.handleClick}>a</li>
<li id="2" onClick={this.handleClick}>b</li>
</ul>
<p>progress</p>
<p>{this.state.progress}</p>
<p>progress length</p>
<p>{this.state.progress.length}</p>
<p>score</p>
<p>{this.state.score}</p>
</div>
);
}
}
Parent component:
import React from 'react';
import ReactDOM from 'react-dom';
import {Child} from './components/Child';
class Parent extends React.Component {
render() {
return (
<Child />
);
}
}
ReactDOM.render(
<Parent />,
document.getElementById('app')
);
Any valid insight / explanation on why is this hapening would be highly appreciated. What puzzles me is that when I type in the console:
var b = 1;
function c() {
b=b+2;
d();
}
function d() {
console.log(b);
}
c();
This returns 3 as expected.
If you know this question to have a duplicate please leave a comment in order for me to remove it.