Reputation: 192
I am creating an application which has user profiles. If a user decides to delete their profile (by clicking "Delete Profile" button), it should send a DELETE request to my backend server, then route the user to a "/about" page of my application. The code structure I have is below:
import React, { Component } from "react";
import { render } from "react-dom";
class Profile extends Component {
constructor(props) {
super(props);
this.state = {
};
this.deleteProfile = this.deleteProfile.bind(this);
}
deleteProfile() {
// props contains all the necessary information to construct the request
// send request to backend server to delete the profile
// route to /about page
}
render() {
return (
<button onClick={this.deleteProfile}>Delete Profile</button>
);
}
}
export default Profile;
I haven't been able to find a solution on how to route the user to a URL after they click the Delete Button. Any suggestions on how to do this?
Upvotes: 1
Views: 215
Reputation: 2085
You should be abe to make use of the Fetch API.
deleteProfile() {
// props contains all the necessary information to construct the request
const { data, url } = this.props
// ES6 and asuming you want to pass the id of in the req body
// data should looks like an obj -> { id : 'im_id000x' }
const body = { ...data }
const headers = new Headers()
const deleteURL = 'mydomain.net/profile_image' // it should have http:// or https://
const redirectURL = 'https://google.de'
headers.append('Content-Type', 'application/json')
// Assuming the API requires a DELETE method
const config = { method: 'DELETE', headers, body: JSON.stringify(body), redirect: 'follow' }
// Send request to backend server to delete the profile
fetch(`deleteURL`, config)
.then(res => res.json()) // assuming the server response is a JSON
.then(parsedRes => console.log(parsedRes))
.then(() => {
// route to /about page
window.location.href = `${redirectURL}`
})
.catch(err => console.error(err.message ? err.message : err))
}
Upvotes: 2