React hook - useEffect - fetching data P2

Sử dụng react-hook và axios để lấy danh sách 1 bài viết với id do người dùng nhập vào
- useEffect là 1 hàm, nhận 2 tham số
- Tham số thứ nhất bắt buộc truyền vào là 1 hàm, hàm này để get data
- Sử dụng thư viện: axios
- Phương thức: GET
- URL: https://jsonplaceholder.typicode.com/posts/${id}
- Tham số thứ hai là mảng, truyền state id vào
- Khi id ở tham số thứ hai thay đổi thì hàm ở tham số thứ nhất sẽ gọi lại
// HookFetching.js
import { useState, useEffect } from 'react'
import axios from 'axios'
export default function HookFetching() {
const [post, setPost] = useState({})
const [id, setId] = useState('')
const handleChange = (e) => setId(e.target.value)
useEffect(() => {
if (id === '') {
setPost({})
return
}
axios
.get(`https://jsonplaceholder.typicode.com/posts/${id}`)
.then(res => setPost(res.data))
.catch(err => console.log(err))
}, [id])
return (
<>
ID: <input type="text" value={id} onChange={handleChange} />
<div>{post.title}</div>
</>
)
}
Ví dụ tương đương với componentDidUpdate trong class
// ClassFetching.js
import { Component } from 'react'
import axios from 'axios'
export default class ClassFetching extends Component {
constructor(props) {
super(props)
this.state = {
post: [],
id: ''
}
}
handleChange = e => this.setState({ id: e.target.value })
componentDidUpdate(prevProps, prevState) {
if (prevState.id !== this.state.id) {
if (this.state.id === '') {
this.setState({ post: {} })
return
}
axios
.get(`https://jsonplaceholder.typicode.com/posts/${this.state.id}`)
.then(res => this.setState({ post: res.data }))
.catch(err => console.log(err))
}
}
render() {
const { id, post } = this.state
return (
<>
ID: <input type="text" value={id} onChange={this.handleChange} />
<hr />
<div>{post.title}</div>
</>
)
}
}
