I made a website that was done using JQuery but I am now trying to learn react but not sure how I would use axios to connect with my backend API. Does anyone know the equivalent of this to axios.
$("#log-form").submit(function (event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: '/users/login',
dataType: 'json',
data: {
'user_name': event.target.inputUsername.value,
'password': event.target.inputPassword.value
},
success: function(token){
$(location).attr('href', '/feed' ); // Redirect to logged in page
},
error: function(errMsg) {
swal(
'Oops...',
errMsg.responseJSON.body,
'error'
)
}
});
});
To change to axios..
axios.post ('users/login', {
User_name: event.taget.whatever,
Password: event.taget.whatever
})
.then (response => {
//whatever you want to do with data you recieved
};
Basically, you'll want to set up a React controlled form.
Axios utilizes promises, so you use can use async/await
inside of a try/catch
block or use the more traditional .then/.catch
.
Note: Always catch
your promises. A common mistake among beginning developers is to just assume the server is never going to throw an error. As a result, it can crash the entire application.
After you have set up your controlled form, you'll create a custom handleSubmit
class method callback with your API call:
constructor() {
super();
this.state = {
error: "",
password: "",
username: ""
}
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault(); // in this case, e.preventDefault() prevents the page from refreshing
const { username, password } = this.state; // grabs current input values from React state
axios.post('/users/login', { user_name: username, password: password }) // sends a POST request to "/users/login" with data
.then(token => { // if the POST request was successful...
// do whatever you need to do with the token (set it to localStorage or Redux state)
this.props.history.push("/feed"); // then you'll redirect -- this assumes you're at the parent component AND using react-router-dom
})
.catch(err => this.setState({ error: err.toString() })); // if there's an error, you'll set it to state and display it in the render method below
}
render() {
return (
<div>
<form onSubmit={this.handleSubmit}>
...etc
<form>
{this.state.error &&
<p>
This was a problem logging in: {this.state.err}
</p>
}
</div>
)
}