Skip to content

Instantly share code, notes, and snippets.

@Danielshow
Created June 1, 2019 00:07
Show Gist options
  • Save Danielshow/d1250329d5c7511de4ecb1918de2255a to your computer and use it in GitHub Desktop.
Save Danielshow/d1250329d5c7511de4ecb1918de2255a to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import logo from './logo.svg';
import { addTodo, deleteTodo } from "./action";
import { connect } from "react-redux";
import './App.css';
class App extends Component {
state = {
todo: '',
todos: []
}
handleChange = (e) => {
this.setState({
todo: e.target.value
})
}
handleSubmit = (e) => {
e.preventDefault()
this.props.addTodo(this.state.todo)
this.setState({
todos: this.props.todos,
todo: ''
})
}
handleDelete = async (id) => {
await this.props.deleteTodo(id)
this.setState({
todos: this.props.todos
})
}
render() {
const listOfTodos = this.state.todos.map(todo => {
return (
<div key={todo.id}>
<li key={todo.id}>{todo.todo} <button onClick={() => this.handleDelete(todo.id)}> Delete Todo</button></li>
</div>
)
})
return (
<div className="App">
<header className="App-header">
<h1>Todo App</h1>
<form onSubmit={this.handleSubmit}>
<label>My Todo: </label> <br />
<input type='text' id='todo' value={this.state.todo} onChange={this.handleChange} autoFocus={true} />
<br />
<button type='submit'>Add Todo</button>
</form>
<h3><u>List of Todo</u></h3>
<ul>
{listOfTodos}
</ul>
</header>
</div>
);
}
}
const mapStateToProps = state => ({
todos: state.todos
});
const mapDispatchToProps = dispatch => ({
addTodo: todo => dispatch(addTodo(todo)),
deleteTodo: id => dispatch(deleteTodo(id))
});
export default connect(mapStateToProps, mapDispatchToProps)(App)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment