Kai Keanaaina Kai Keanaaina - 1 month ago 13
React JSX Question

How to change page in a Promise using React

I'm using Reactjs. I have a form that will populate my database onSubmit with just a name property. Assuming inserting data is success, How do I jump to back to my landing page in the promise? my landing page url is a simple '/'. or should i jump back to the landing page somewhere else and not in the promise.



const React = require('react')
const axios = require('axios')

class AddNewRecordLabel extends React.Component {
constructor (props) {
super(props)
this.state = ({
artists: []
})
this.onSubmit = this.onSubmit.bind(this)
}
componentDidMount () {
axios.get('http://localhost:5050/recordLabels')
.then((res) => {
this.setState({
artists: res.data
})
})
}
onSubmit (e) {
e.preventDefault()
if (!this.refs.name.value) {
console.log('fill in the name input')
} else {
var object = {
name: this.refs.name.value
}
axios.post('http://localhost:5050/recordLabels', object)
.then((res) => {
//change here
})
}
}
render () {
return (
<div>
<h3>add new record label</h3>
<form onSubmit={this.onSubmit}>
<label>
<input type='text' ref='name' placeholder='name'/>
</label>
<br></br>
<button type='submit'> Add Record Label </button>
</form>
</div>
)
}
}

module.exports = AddNewRecordLabel




Answer

Typically, you would create a library using a flux pattern which uses dispatchers, actions and stores to control your components. If you want to save a lot of time, there are libraries using the flux pattern out there such as react-redux and react-flux.

I have used a home grown flux pattern before. I'm using redux now which is fairly easy to use as well as pretty quick to develop with from my personal experience. There's great documentation on it and a lot of support from the community.

If you want to keep it simple, you might want to rethink your strategy such as returning message that either replaces the form giving them options such as going back to the home page or even leaves the form so they have an opportunity to add another record label. You would also want to check to see if there was an error and show some sort of message stating why it was unsuccessful based on the response. If you want to go back to the home page you could simply add this to your promise...

window.location.href = '/'

...but ideally, you would want to move your service calls to another file and return responses, then act on those responses in your component accordingly, but the general recommended approach is to do it by dispatchers and listeners and update your state or props within this component.

Comments