Reputation: 217
import React, { Component } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import { Button } from "react-bootstrap";
export default class DeleteTodo extends Component {
constructor(props) {
super(props);
this.state = {
todo_description: "",
todo_responsible: "",
todo_id: this.props.match.params.id,
};
console.log(this.props.match.params.id);
}
onSubmit(e) {
e.preventDefault();
axios
.post("http://localhost:4000/todos/delete/" + this.props.match.params.id)
.then((res) => console.log(res.data));
this.props.history.push("/");
}
render() {
console.log(this.props.match.params.id);
return (
<div>
<h3 align="center">Confirm Delete</h3>
<form onSubmit={this.onSubmit}>
<div>
<b className="d-inline">Description: </b>
<p className="d-inline">{this.state.todo_description}</p>
</div>
<div>
<b className="d-inline">Responsible: </b>
<p className="d-inline">{this.state.todo_responsible}</p>
</div>
<br />
<div>
<Button size="sm" type="submit" variant="danger">
Delete
</Button>
 
<Link to={"/"}>
<Button size="sm" variant="info">
Undo
</Button>
</Link>
</div>
</form>
</div>
);
}
}
I want to add the object's ID to the Axios post route.
console.log(this.props.match.params.id); will log the ID in the constructor and in the render, but props is showing undefined in the Axios call. How do I get the ID to renter inside onSubmit()?
Upvotes: 0
Views: 32
Reputation: 310
Your issue is that your onSubmit
function doesn't have the same this
variable as the native react functions. In order to solve this, you need to bind the function with the component object.
You can read more about this here: https://reactjs.org/docs/handling-events.html
Replace your file with the below:
import React, { Component } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import { Button } from "react-bootstrap";
export default class DeleteTodo extends Component {
constructor(props) {
super(props);
this.state = {
todo_description: "",
todo_responsible: "",
todo_id: this.props.match.params.id,
};
this.onSubmit = this.onSubmit.bind(this) // new line added
console.log(this.props.match.params.id);
}
onSubmit(e) {
e.preventDefault();
axios
.post("http://localhost:4000/todos/delete/" + this.props.match.params.id)
.then((res) => console.log(res.data));
this.props.history.push("/");
}
render() {
console.log(this.props.match.params.id);
return (
<div>
<h3 align="center">Confirm Delete</h3>
<form onSubmit={this.onSubmit}>
<div>
<b className="d-inline">Description: </b>
<p className="d-inline">{this.state.todo_description}</p>
</div>
<div>
<b className="d-inline">Responsible: </b>
<p className="d-inline">{this.state.todo_responsible}</p>
</div>
<br />
<div>
<Button size="sm" type="submit" variant="danger">
Delete
</Button>
 
<Link to={"/"}>
<Button size="sm" variant="info">
Undo
</Button>
</Link>
</div>
</form>
</div>
);
}
}
Upvotes: 1