-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Project Basic React #29
Labels
Comments
haydanu
assigned brantem, dearetta, krowter, chumaidi, fadhilahade, trie168, Darrengobel, Sumapraja, zakysyahab14 and aditilham
Jul 3, 2019
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;
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: