React hook - useReducer - Fetching data

React hook - useReducer - Fetching data

·

2 min read

1. Thông tin chung

  • Sử dụng useEffect để lấy data
  • Sử dụng axios để call API
  • Phương thức GET
  • URL: jsonplaceholder.typicode.com/posts/1
  • Sử dụng useReducer để quản lí state

2. Cách làm

2-1. Thêm các thư viện cần thiết

import {useEffect, useReducer} from 'react'
import axios from 'axios'

2-2. Khởi tạo state ban đầu

const initialState = {
  loading: true,
  post: {},
  error: ''
}

2-3. Tạo hàm reducer

  • Hàm này nhận 2 tham số
  • Tham số 1 là state muốn thay đổi giá trị
  • Tham số 2 là action
  • Tùy vào loại action mà thay đổi state tương ứng
const reducer = (state, action) => {
  switch (action.type) {
    case 'FETCH_DATA_SUCCESS':
      return {
        ...state,
        loading: false,
        post: action.payload.data,
        error: ''
      }      
    case 'FETCH_DATA_FAILURE':
      return {
        ...state,
        loading: false,
        post: {},
        error: action.payload.error
      }

    default:
      return {...state}
  }
}

2-4. Sử dụng useReducer

  • Hàm useReducer nhận 2 tham số
  • Tham số 1 là hàm reducer ở bước 2-3
  • Tham số 2 là biến initialState ở bước 2-2
  • Hàm useReducer trả về mảng 2 phần tử
  • Phần tử 1 là giá trị của state
  • Phần tử 2 là hàm để thay đổi state
const [state, dispatch] = useReducer(reducer, initialState)

2-5. Sử dụng useEffect

  • Hàm useEffect nhận 2 tham số
  • Tham số 1 là hàm xử lí lấy data
  • Tham số 2 là mảng rỗng để chỉ lấy data 1 lần
useEffect(() => {
  axios
    .get('https://jsonplaceholder.typicode.com/posts/1')
    .then(response => {
      dispatch({
        type: 'FETCH_DATA_SUCCESS',
        payload: { data: response.data }
      })
    })
    .catch(error => {
      dispatch({
        type: 'FETCH_DATA_FAILURE',
        payload: { error: error.message }
      })
    })
}, [])

3. Demo