Create a reusable component for your HTTP client service.
// httpService.js
import axios from "axios"
axios.interceptors.response.use(null, error => {
const expectedError =
error.response &&
error.response.status >= 400 &&
error.response.status < 500;
if (!expectedError) {
console.log("Logging the error", error);
alert("An unexpected error occurred");
}
return Promise.reject(error);
});
export default {
get: axios.get,
post: axios.post,
put: axios.put,
delete: axios.delete
};
Below is an example of a registration post request to the user information
// authService.js
import http from "../services/httpService"
import { apiUrl } from "../../config.json"
const apiEndPoint = apiUrl + "";
export function register(user) {
return http.post(apiEndPoint, {
firstname: user.firstname,
secondname: user.secondname,
email: user.email,
phone: user.phone,
password: user.password,
});
}
N.B. Config.json file contains your API URL.
Below is an example of a registration form component that has a doSubmit method for calling the server and navigating to a login page after a successful registration.
...
doSubmit = async () => {
// Call Server
try {
await userService.register(this.state.data);
this.props.history.push("/Login"); // Programmatic Routing
} catch (ex) {
if (ex.response && ex.response.status === 400) {
const errors = { ...this.state.errors };
errors.username = ex.response.data;
this.setState({ errors });
}
}
....
This example is made for illustration purposes, and it could be modified accordingly to your API requests.