iT邦幫忙

2022 iThome 鐵人賽

DAY 12
0
Modern Web

React應用記錄誌系列 第 12

Day12 實作練習Axios

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20220927/20139800BcRts1DIbz.png

App.js

import React from 'react'
import Part from './component/Part'
const App = () => {
  return (
    <div>
    <h1><Part /></h1>
    </div>
  )
}
export default App

Part.js

import React from 'react'
import useAxios from '../hooks/useAxios';
import axios from '../api/axiosinstance';

const Part = () => {const[chil,error,loading,refetch] = useAxios({
    axiosInstance:axios,
    method:'GET',
    url:'/',
    requestConfig:{
      hesders:{
         'Content-Language':'en-US'            
      }
    }
})
return (
 <div>
    <h4>Axios Requests</h4>
    {loading && <p>Loading...</p>}
    {!loading && error && <p className='errMsg'>{error}</p>}
    {!loading && !error && chil && <p>{chil?.chil}</p>}
    {!loading && !error && !chil && <p>No data display</p>}
    <button onclick={() => refetch()}>Test</button>
 </div>
)
}
export default Part

useAxios.js

import { useState, useEffect } from "react";
const useAxios = (configObj) => {
    const {
        axiosInstance,
        method,
        url,
        requestConfig = {}
    } = configObj;

    const [response, setResponse] = useState([]);
    const [error, setError] = useState('');
    const [loading, setLoading] = useState(true);
    const [reload, setReload] = useState(0);

    const refetch = () => setReload(prev => prev + 1);
    useEffect(() => {
        //let isMounted = true;
        const controller = new AbortController();

        const fetchData = async () => {
            try {
                const res = await iosInstance[method.toLowerCase()](url, {
                    ...requestConfig,
                    signal: controller.signal
                });
                console.log(res);
                setResponse(res.data);
            } catch (err) {
                console.log(err.message);
                setError(err.message);
            } finally {
                setLoading(false);
            }
        }
      fetchData();
        return () => controller.abort();
        // eslint-disable-next-line
    }, [reload]);

    return [response, error, loading, refetch];
}
export default useAxios

axiosinstance.js

import axios from 'axios';
const BASE_URL = 'https://icanhazdadjoke.com';

export default axios.create({
    baseURL: BASE_URL,
    headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
});

上一篇
Day 11 實作練習 Redux
下一篇
Day13 Redux Dev Tools
系列文
React應用記錄誌31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言