UpdateおよびDelete機能の実装
コードを以下に示します.
import React from 'react';
import firebase from './Firebase/firebase';
import { SHOW } from '../constants/routes';
class Update extends React.Component {
constructor(props) {
super(props);
this.state = {
title: '',
detail: '',
deadline: '',
}
this.ref = firebase.database().ref('tasks');
this.handleChange = this.handleChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.deleteTask = this.deleteTask.bind(this);
}
componentDidMount() {
const ref = this.ref.child(this.props.match.params.id);
ref.once('value', (snapshot) => {
const task = snapshot.val();
this.setState({
...task
})
})
}
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
onSubmit() {
const { title, detail, deadline } = this.state;
const updateRef = this.ref.child(this.props.match.params.id);
updateRef.update({
title,
detail,
deadline
}).then(() => {
this.setState({
title: '',
detail: '',
deadline: '',
});
this.props.history.push(SHOW);
}).catch(error => {
console.log("Error: ", error);
})
}
deleteTask() {
const removeRef = this.ref.child(this.props.match.params.id);
removeRef.remove().then(() => {
console.log("Remove Succeeded");
this.props.history.push(SHOW);
}).catch((error) => {
console.log("Remove failed:" + error.message);
})
}
render() {
return (
<div>
<h4>タスク更新・削除</h4>
<form>
<table>
<tbody>
<tr>
<td>タイトル:</td>
<td><input type="text" name="title" value={this.state.title} onChange={this.handleChange}></input></td>
</tr>
<tr>
<td>タスク名:</td>
<td><input type="text" name="detail" value={this.state.detail} onChange={this.handleChange}></input></td>
</tr>
<tr>
<td>期限:</td>
<td><input type="date" name="deadline" value={this.state.deadline} onChange={this.handleChange}></input></td>
</tr>
</tbody>
</table>
</form>
<table>
<tbody>
<tr>
<td><button type="submit" onClick={this.onSubmit} >タスク更新</button></td>
<td><button onClick={this.deleteTask}>削除</button></td>
</tr>
</tbody>
</table>
</div >
)
}
}
export default Update;
コメント