컴포넌트 데이터 주고 받기 1

리엑트 데이터 주고 받는 패턴 - 해야할 일 추가하기

Todos는 React JS Crash Course (2019)을 진행하면서 만든 리엑트 웹이다. 큰 기능들은 해야할 일들을 작성하고, 삭제하고, 체크하는 기능이 있다.

Data from json placeholder

위의 사이트에서 아래와 같은 코드와 post 등 간단한 기능들을 제공해준다.

[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false
  },
  {
    "userId": 1,
    "id": 3,
    "title": "fugiat veniam minus",
    "completed": false
  }
  ...
]

App.js

state = {
    todos:[
      {
        id: 1,
        title: 'Take out the trash',
        completed: false
      },
    ]
}
    /* SET state in client-side */

componentDidMount(){
    axios.get('https://jsonplaceholder.typicode.com/todos?_limit=10')
    /* LINK data from the web */
        .then(res => this.setState({ todos: res.data })) 
    /* THEN get data from the web */
}

addTodo = (title) => {
    axios.post('https://jsonplaceholder.typicode.com/todos',{
      title,
      completed: false
    })
    /* POST data to the web */
        .then(res => this.setState({ todos: [...this.state.todos, res.data] }))
    /* THEN update data to state and the web */
}
<Router>
    <Route exact path="/" render={props => (
        <React.Fragment>
            <AddTodo addTodo={this.addTodo} />
            {/* COMMUNICATE data using attribute */}
            <Todos todos={this.state.todos} markComplete={this.markComplete} delTodo={this.delTodo}/>
        </React.Fragment>
        )} 
    />
    <Route path="/about" component={About} />
</Router>

AddTodo.js (<AddTodo /> component)

state = {
    title: ''
}
//INPUT the values in this state

onSubmit = (e) => {
    e.preventDefault();
    this.props.addTodo(this.state.title);
    this.setState({title: ''});
}
//PREVENT deafult event

onChange = (e) => {
    this.setState({[e.target.name]: e.target.value})
//TRIGGER event when the target.value changed
//SET state in object format
}

render() {
    return (
        <form onSubmit={this.onSubmit} style={{ display: 'flex' }}>
            <input 
                type = "text"
                name = "title"
                style = { {flex: '10', padding: '5px'} }
                placeholder = "Add Todo..." 
                value = {this.state.title}
                onChange = {this.onChange}
            />
            <input 
                type = "submit"
                value = "Submit" 
                className = "btn"
                style = {{flex: '1'}}
            />
        </form>
    )
}