1

I have a question about es6 arrow functions for promises (in my example in react). In my sample code, I simply want to call a function insight another function. It only works if I use es6. I've been reading online but I don't exactly understand why it only works with es6.

class App extends React.Component {
constructor(props) {
    super(props);
    this.state = {
    }
    this.handleInput = this.handleInput.bind(this);
    this.testing = this.testing.bind(this);
}

testing(){
console.log("hello")
}

handleInput(){
    ...
.then(function(){
    this.test() //doesnt work
    test() //doesnt work
})
.then => res{
// I actually don't require parameters, but it's
// never working unless I use this syntax
.this.test() // WORKS
}
}

  render() {
    return (
      <div>
        Hello {this.props.name}
      </div>
    );
  }
}
halfer
  • 19,824
  • 17
  • 99
  • 186
javascripting
  • 1,135
  • 4
  • 25
  • 46

2 Answers2

3

Because you are loosing the context for native functions.

Let me explain. If you r calling func like 'this.test()' for 'function test()' you call it from the current call context. So the 'this' keyword would contain the context environment of the function-caller. Arrow functions, for the flip side, always match the context to the object, or function, where they have been created.

Dmitriy Kovalenko
  • 3,437
  • 3
  • 19
  • 39
0

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)
simbathesailor
  • 3,681
  • 2
  • 19
  • 30