React Axios with useFetch

上禮拜參加一家公司的面試,

因為剛打完疫苗,

整個很不舒服....完全不能思考,....

所以基本上答題錯誤百出...


今天身體有比較好了,

花一點時間來把試題完成.

覺得自己一定要把它寫出來不可~


因為對方是給 github api

我發現,

不寫 options {method, params, headers}

也可以抓到資料

所以就直接這樣寫(對, 我很懶 ><):


useAxios.tsx

import { useState, useEffect } from "react";
import axios from "axios";

// 撰寫一個 hooks 來獲取 api
function useAxios(url: string) {
// 判斷是否讀取中, 初始值為 false
const [isLoading, setIsLoading] = useState<boolean>(false);
// 宣告data 為 any
const [data, setData] = useState<any>({});
// 宣告 err 為字串
const [err, setErr] = useState<string>("");

useEffect(() => {
axios
.get(url)
.then(res => {
console.log(res.data);
setData(res.data);
})
.catch(err => setErr(err))
.finally(() => setIsLoading(false));
}, [url]);

return { isLoading, data, err };
}

export default useAxios;


layout.tsx

import React from "react";
import useAxios from "./useAxios";
import "./App.css";

function Layout() {
const { isLoading, data, err } = useAxios(
"https://api.github.com/search/repositories?q=react"
);

{
if (isLoading) {
return <h1>is loading......</h1>;
} else if (err) {
return <h1>data can't fetch: {err}</h1>;
} else {
return (
<div className="wrap">
<div className="flexBox">
{Array.isArray(data.items)
? data.items.map((i: any, index: number) => {
return (
<div key={index} className="inBox">
<p>id: {i.id}</p>
<p>name: {i.name}</p>
<p>owner login:{i.owner.login}</p>
<p>owner id:{i.owner.id}</p>
</div>
);
})
: null}
</div>
</div>
);
}
}
}

export default Layout;


App.css

.wrap {
width: 100vw;
height: 100vh;
padding: 10px 20px;
}
.flexBox {
display: flex;
justify-content: center;
align-content: center;
width: 100vw;
flex-wrap: wrap;
padding: 10px;
}
.inBox {
margin: 7px;
width: 13rem;
padding: 2px 12px;
background-color: #dcdcdd;
border-radius: 3px;
box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);
}

api 資料結構

取第一層和第二層



這是其中一項解法!

在 teamwork 狀況下

應該不會這樣寫

因為 api 基本上都會封裝


類似這樣

import { promiseHandle } from '../promiseHandle';
import { urlReplace, urlDevice } from '../utils';

/**
 * 後台內容管理項目 相關 api
 */

// 選單
export function getApiMenu(params = {}) {
  return promiseHandle({
    apiName: 'getApiMenu',
    url: urlDevice('/menus'),
    method: 'get',
    params,
  });
}


好啦 今天就先做到這,

有機會再分享 謝謝





留言

熱門文章