Pradeep
Pradeep

Reputation: 59

How to bind a function within itself in Javascript

i want to bind function within itself like so that i can change state using this setState help me resolve this function(response){ this.function=this.function.bind(this) console.log(response) }

Upvotes: 0

Views: 373

Answers (3)

Sanaullah
Sanaullah

Reputation: 374

try this hopefully will work for you

axios.post(" http://${REACT_APP_SERVER_URL}/facebook", { uid: user }).then((response) => {
        console.log('hello')
        if (response.data.success) {
            const { checked } = this.state;
            const newChecked = [...checked];
            newChecked.push(1)
            this.setState({ checked: newChecked });
            console.log(this.state.checked)
            history.push("/dashboard");
        }
    }).catch(err=>{
        console.log(err)
    })

Upvotes: 1

ThanhEngineer
ThanhEngineer

Reputation: 1339

Try this to bind your response function

function(response){
     //this.function=this.function.bind(this)
     console.log(response)
 }.bind(this)

Upvotes: 0

chipit24
chipit24

Reputation: 6987

Binding a function within itself is a confusing thing to do; you're modifying the function and it probably won't do what you expect the next time it's called. Your question is a classic example of the XY problem.

What you are probably looking for is described in the React docs at https://reactjs.org/docs/faq-functions.html#how-do-i-bind-a-function-to-a-component-instance.

You have two options, call bind, or use an arrow function:

class MyComponent extends Component {
  constructor() {
    /* Bind the value of this */
    this.myFunction = this.myFunction.bind(this);
  }

  render() {
    <div>
      {/* Or use an arrow function */}
      <button onClick={() => this.myFunction()}>My button</button>
    </div>
  }
}

Upvotes: 0

Related Questions