It all about context. when you are using non-arrow function context set is the new one, not the one inherited from outside function. If you use arrow function in then it will work as expected. context will be that of outside.
See this example, how arrow function can persist contexts
const PollOption = ({options,selected, onChange, myTest}) => {
console.log("addafafdj", myTest)
return (
<div className="pollOption">
{options.map((choice, index) => (
<label key={index}>
<input type="radio"
name="vote"
key={index}
onChange={(e)=>onChange(e,index)}/>
{choice.tag}
</label>
))}
</div>
);
};
const VoteCount = ({totalVotes, options}) =>{
return(
<div className="VoteCount">
<h2>Total Votes {totalVotes}</h2>
<ul>
{options.map((element,index)=>(
<li>{element.tag}: {element.count}</li>
))}
</ul>
</div>
);
}
class OpinionPoll extends React.Component{
constructor(props) {
super(props);
this.state = {
selectedOption: 0,
totalVotes: 0,
choiceOneVotes: 0,
choiceTwoVotes: 0,
options: [
{tag:"A", count:0},
{tag:"B", count:0},
{tag:"C", count:0},
{tag:"D", count:0}
]
}
}
handleClick(){
console.log('submitted option', this.state.selectedOption);
this.setState(prevState => {
return {totalVotes: prevState.totalVotes + 1}
})
const selectedIndex = this.state.selectedOption
const newOption = [...this.state.options]
debugger
newOption[selectedIndex].count += 1
this.setState({
options: newOption,
})
}
test(value) {
console.log("promise worked", value)
}
handleOnChange(e,index){
console.log('selected option', index);
this.setState({
selectedOption: index
});
const newPromise = new Promise((resolve,reject)=> {
setTimeout(()=> {
resolve("11232")
},1000)
})
newPromise.then((value)=> {
this.test(value)
})
console.log("state in handlechange",this.state)
}
render(){
const myTest = "hola boy"
return (
<div className="poll">
{this.props.model.question}
<PollOption
myTest
options={this.state.options}
onChange={(e,index) => this.handleOnChange(e,index)}
selected={this.state.selectedOption}/>
<button onClick={() => this.handleClick()}>Vote!</button>
<VoteCount
totalVotes={this.state.totalVotes}
options={this.state.options}
/>
</div>
);
}
}
var json = {
question: 'Do you support cookies in cakes?',
choices:
[
{text: "Yes", value: "yes"},
{text: "No", value: "no"}
]
}
const root = document.getElementById("root");
ReactDOM.render(<OpinionPoll model ={json} />, root)
//ReactDOM.render(<div>test </div>, root)