0

How we can call react set state from Sync callback function for example

MyClass.getAynchFunction(inputParam, function (err, data) {
     if (err) console.log(err, err.stack); // an error occurred
     else {
         console.log(JSON.stringify(data))
     }
} 

I want to set variable from 'data' object in react component state.

2
  • Where is MyClass.getAynchFunction executed? Commented Jan 17, 2020 at 12:08
  • thats a seperate class Commented Jan 17, 2020 at 12:13

1 Answer 1

1

It's a bit of a guess because you're not specifying what exactly doesn't work, but I'm guessing you're getting something like this.setState is not a function.

That's because this isn't the React component inside your callback function. There's basically two ways to fix this

// Bind the current this to the callback function.
MyClass.getAyncFunction(
  "input",
  function(err, data) {
    this.setState({ responseData: data });
  }.bind(this)
);

// Rewrite it as an arrow function so the current this is automatically bound.
MyClass.getAyncFunction("inputParams", (err, data) => {
  this.setState({ responseData: data });
});

I would go with the arrow function because it's cleaner.

Sign up to request clarification or add additional context in comments.

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.