Open haydanu opened 5 years ago
import React from "react";
import "./App.css";
import axios from "axios";
const API = "http://haekal-todo-list-api.herokuapp.com/todos";
class App extends React.Component {
constructor() {
super();
this.state = {
posts: [],
editTodo: false,
showingTodo: true,
description: "",
id: ""
};
}
// to fetch data for first time
componentDidMount() {
axios.get(`${API}`).then(response => {
console.log(response);
this.setState({
posts: response.data
});
});
}
// to delete todo based on index
// pass index argument
deleteTodo = index => {
axios.delete(`${API}/${index}`).then(response => {
this.setState({
posts: response.data
});
if (response.status == 200) {
alert("data berhasil dihapus");
}
});
};
// to open input and hide the list
// and catch list value to pass into input element
toggleEdit = (description, id) => {
this.setState({
editTodo: true,
showingTodo: false,
description,
id
});
};
// edit todo
// hide input and open list again
editTodo = index => {
axios
.put(`${API}/${index}`, {
description: this.state.description
})
.then(response => {
this.setState({
posts: response.data,
editTodo: false,
showingTodo: true,
id: ""
});
if (response.status === 200) {
alert("data berhasil diupdate");
}
});
};
//handle input change
handleChange = event => {
this.setState({
description: event.target.value
});
};
render() {
return (
<div className="App">
<h1>My Posts</h1>
{/*
*render list todo
*/}
{this.state.posts.map((data, index) => {
return (
<div key={index}>
<ul>
<li>
{/*
* open input when edit is clicked
* and hide this input when update is clicked
*/}
{this.state.id === index && (
<div>
<input
value={this.state.description}
onChange={this.handleChange}
name="description"
/>
</div>
)}
{/*
* hide list when edit is clicked
* open list when update is clicked
*/}
{this.state.showingTodo && <div>{data.description} </div>}
{/*
* delete todo and pass index as a parameter
*/}
<div onClick={() => this.deleteTodo(index)}>delete</div>
{/*
* toggle edit and update element
*/}
{this.state.id === index ? (
<div onClick={() => this.editTodo(index)}>update</div>
) : (
<div
onClick={() => this.toggleEdit(data.description, index)}
>
edit
</div>
)}
</li>
</ul>
</div>
);
})}
</div>
);
}
}
export default App;
https://github.com/Darrengobel/projectreactbasic