Skip to content

Commit

Permalink
feat: 新增useFetch hook
Browse files Browse the repository at this point in the history
  • Loading branch information
mianmalife committed Jun 30, 2024
1 parent 8dc78d1 commit 06b4a90
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 20 deletions.
7 changes: 7 additions & 0 deletions src/components/ErrorComp.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default function ErrorComp({error}) {
error = error || {}
return <>
<p className="text-red-500 text-center">{error.status || ''}</p>
<p className="text-red-500 text-center">{error.statusText || '系统错误'}</p>
</>
}
41 changes: 41 additions & 0 deletions src/hook/useFetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { useEffect, useState } from "react";

export default function useFetch(url, options) {
const [data, setData] = useState()
const [loading, setLoading] = useState(false)
const [error, setError] = useState()
options = options || {}
useEffect(() => {
const controller = new AbortController()
const fetchData = async () => {
if (url) {
try {
setLoading(true)
const response = await fetch(url, {...options, signal: controller.signal})
if (response.ok) {
const resp = await response.json()
setData(resp)
} else {
setError(response)
}
} catch (error) {
console.warn(error)
if (error !== 'cancle ask') {
setError(error)
}
} finally {
setLoading(false)
}
}
}
fetchData()
return () => {
controller.abort('cancle ask')
}
}, [url])
return {
loading,
data,
error
}
}
28 changes: 8 additions & 20 deletions src/pages/demo/demo.jsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { useState, useEffect, useRef, useReducer } from "react"
import useFetch from "@/hook/useFetch"
import { v4 as uuidv4 } from 'uuid'
import TaskItem from "./TaskItem"
import BirdTabItem from "./BirdTabItem"
import BirdList from './BirdList'
import ErrorComp from "@/components/ErrorComp"
import LottieSpin from "../../components/LottieSpin"
import loadingUrl from './loading.json?url'

Expand Down Expand Up @@ -36,28 +38,12 @@ const group = ['person role', 'animal-bird', 'body', 'objects']
function Demo() {
const taskRef = useRef('')
const [taskList, dispatch] = useReducer(reducer, [])
const [birdList, setBirdList] = useState([])
const [active, setActive] = useState('person role')
const [loading, setLoading] = useState(true)
const taskInputRef = useRef()
const {loading, data, error} = useFetch(`https://emojihub.yurace.pro/api/all/group/${active}`)
useEffect(() => {
taskInputRef.current.focus()
}, [])
useEffect(() => {
const fetchList = async () => {
try {
setLoading(true)
const data = await fetch(`https://emojihub.yurace.pro/api/all/group/${active}`).then(res => res.json())
setBirdList(data)
} catch (error) {
console.warn(error)
setBirdList([])
} finally {
setLoading(false)
}
}
fetchList()
}, [active])
function handleKeyUp(e) {
if (e.keyCode === 13) {
if (!taskRef.current.trim()) return
Expand Down Expand Up @@ -96,9 +82,11 @@ function Demo() {
<ul className="flex items-center fsizes-14">
{group.map(item => <BirdTabItem key={item} item={item} active={active} handleTabItem={handleTabItem} />)}
</ul>
{!loading ? <ul className="divide-y h-80 overflow-y-auto">
<BirdList data={birdList} />
</ul> : <LottieSpin path={loadingUrl} />}
{!loading && !error && <ul className="divide-y h-80 overflow-y-auto">
<BirdList data={data || []} />
</ul>}
{!loading && error && <ErrorComp error={error} />}
{ loading && <LottieSpin path={loadingUrl} />}
</div>
</div>
)
Expand Down

0 comments on commit 06b4a90

Please sign in to comment.