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)
}
-
1is this an anonymous function or a class method?Phillip– Phillip2019-07-13 16:30:23 +00:00Commented Jul 13, 2019 at 16:30
Add a comment
|
3 Answers
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)
})
5 Comments
Pradeep
the function is in then/promise so it is showing error if i use const
Sanaullah
can you add the complete function where you using this
Pradeep
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"); } } )chipit24
@user8523065 That is not valid code, and please add it to your actual question as a properly formatted code block.
Sanaullah
@user8523065 I have added the code in my answer try it will work hopefully
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>
}
}