TeodorKolev TeodorKolev - 3 months ago 21
Javascript Question

ReactJs Redirect on state variable change

I am trying to get json via ajax and if my response variable is acceptable redirect using react router. How can I achieve that?

successRedirect(){
if (this.responseCode.equals("what I need")) {
router.transitionTo('/')
}
}

createCheckout() {
$.ajax({
url: "someurl",
dataType: 'json',
type: 'POST',
cache: false,
data: this.data,
success: function(response) {
this.setState({
response: response,
responseCode: response.result.code
});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
})
}


Function must be called after response is taken. For example I have this code and in render response is taken and shown after some time:

render(){
return (
<div>
<div>Response - {this.state.responseCode}</div>
</div>
);
}

Answer

It appears the issue was with this line:

if (this.responseCode.equals("what I need")) {

Items that get added via this.setState are available on the this.state object. Also JavaScript does not supply an equals function, but you can do comparisons with ===

if (this.state.responseCode === "what I need") {
Comments