0

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) }

1
  • 1
    is this an anonymous function or a class method? Commented Jul 13, 2019 at 16:30

3 Answers 3

1

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)
    })
Sign up to request clarification or add additional context in comments.

5 Comments

the function is in then/promise so it is showing error if i use const
can you add the complete function where you using this
loginRequest = axios.post( http://${REACT_APP_SERVER_URL}/facebook, { uid:user } ).then( const login=(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"); } } )
@user8523065 That is not valid code, and please add it to your actual question as a properly formatted code block.
@user8523065 I have added the code in my answer try it will work hopefully
0

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>
  }
}

Comments

0

Try this to bind your response function

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.