-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
8dc78d1
commit 06b4a90
Showing
3 changed files
with
56 additions
and
20 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | ||
</> | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters