Skip to content

Commit bb1b09f

Browse files
committed
tech(basic): add hooks directory
1 parent 539c30b commit bb1b09f

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { useState, useEffect } from 'react'
2+
import axios from 'axios'
3+
4+
export default function useFetch(url){
5+
6+
const [response, setResponse] = useState(undefined)
7+
const [error, setError] = useState()
8+
const [loading, setLoading] = useState(false)
9+
10+
useEffect(async () => {
11+
if (!url || url.trim() === '') return
12+
try {
13+
setLoading(true)
14+
const result = await axios.get(url)
15+
setResponse(result.data)
16+
} catch (err) {
17+
setError(err)
18+
} finally {
19+
setLoading(false)
20+
}
21+
}, [url])
22+
23+
return { response, error, loading }
24+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
function useOnlineStatus() {
2+
const [online, setOnline] = useState(window.navigator.onLine)
3+
4+
useEffect(() => {
5+
function handleOnline() {
6+
setOnline(true)
7+
}
8+
function handleOffline() {
9+
setOnline(false)
10+
}
11+
window.addEventListener('online', handleOnline)
12+
window.addEventListener('offline', handleOffline)
13+
return () => {
14+
window.removeEventListener('online', handleOnline)
15+
window.removeEventListener('offline', handleOffline)
16+
}
17+
}, [])
18+
return online
19+
}
20+
21+
export default useOnlineStatus
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { useState } from 'react'
2+
import axios from 'axios'
3+
4+
export default function usePost(url, methodName = 'sendPostData'){
5+
6+
const [response, setResponse] = useState(undefined)
7+
const [error, setError] = useState()
8+
const [loading, setLoading] = useState(false)
9+
10+
const postData = async (payload) => {
11+
if (!url || url.trim() === '') return
12+
try {
13+
setLoading(true)
14+
const result = await axios.post(url, payload)
15+
setResponse(result.data)
16+
} catch (err) {
17+
setError(err)
18+
} finally {
19+
setLoading(false)
20+
}
21+
}
22+
23+
return { response, error, loading, [methodName]:postData }
24+
}

0 commit comments

Comments
 (0)