I have a react applictation with react-router for navagation. I try to create form that is update some data. After submit the data are send to server though ajax request and in case of ajex response is "Ok" than the user has to be redirected to another page (in my case url in react-router is /carwash
) and information about succesfull update has to be shown in the distination page.
I tried to do this by 3 differect ways:
1) this.props.history.push('/carwash')
The result was exception:Uncaught TypeError: Cannot read property 'push' of undefined
2) browserHistory.push("/carwash")
, the result is the list in browser was changed but there isn't any redirection
3) redirection on absolute url w/o react: window.location.replace("/owner.html#/carwash")
, the result was succesfull but I don't undestand how to inform destitaion page the data was update succesfull.
Can you explain me what is the best way for redirection in react and how to use it? And what is not less important how to infom page where the user will be redirected that the data was update succefull ?
My code has the following view:
import React from 'react';
import {Router} from 'react-router';
import Loading from './form/loading.jsx';
export default class EditCarWashForm extends React.Component{
static contextTypes = {
router: React.PropTypes.object.isRequired
};
constructor(props) {
super(props);
this.state = {
name : {value : constants.EMPTY_FIELD, isValid : false},
address : {value : constants.EMPTY_FIELD, isValid : true},
isCarWashDownload : true
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
let carWashData = {some logic}
$.ajax({
url: '/carwash/',
type: 'POST',
async: true,
cache: false,
contentType: 'application/json',
data: JSON.stringify(carWashData),
dataType: 'json',
success: function(data) {
if (data.message == 'Ok'){
// browserHistory.push("/owner.html#/carwash")
this.props.history.push('/carwash');
// window.location.replace("/owner.html#/carwash");
}
}.bind(this),
})
};
render(){
let data = <Loading/>
if (this.state.isCarWashDownload) {
data =
<form onSubmit={this.handleSubmit} id="addCarWashForm">
<FormInputField
title="Name*:"
placeholder="Name"
name="name"
required={true}
maxLength={50}
defaultValue={this.state.name.value}
/>
<FormInputField
title="Adress:"
placeholder="Adress"
name="address"
maxLength={200}
/>
<div className="form-group">
<div className="col-sm-offset-2 col-sm-10">
<button type="submit">Update</button>
</div>
</div>
</form>
}
return (
<div>
{data}
</div>
)
}
}