Skip to main content

Command Palette

Search for a command to run...

React hook - useEffect - fetching data P2

Updated
2 min readView as Markdown
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>
      </>
    )
  }
}

Demo online

ReactJS

Part 17 of 19

ReactJS là một thư viện JavaScript mã nguồn mở được thiết kế bởi Facebook để tạo ra những ứng dụng web hấp dẫn, nhanh và hiệu quả với mã hóa tối thiểu. Series hướng dẫn học ReactJS cơ bản.

Up next

React hook - useEffect - fetching data P1

Sử dụng react-hook và axios để lấy danh sách 100 bài viết từ: jsonplaceholder.typicode.com/posts 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...

More from this blog

KenTrung VN

23 posts

Mình mới ba mấy tuổi thôi mà đứng dậy nhanh quá đã hơi chóng mặt 🤪🤪🤪