1
0
mirror of https://github.com/OpenNebula/one.git synced 2025-03-16 22:50:10 +03:00

F OpenNebula/one#5422: Add socket to useFetch hook

This commit is contained in:
Sergio Betanzos 2021-06-23 10:50:49 +02:00
parent c437437b50
commit 20420b0af6
No known key found for this signature in database
GPG Key ID: E3E704F097737136

View File

@ -24,11 +24,13 @@ const INITIAL_STATE = {
const fetchReducer = (state, action) => {
const { type, payload, reload = false } = action
const { data: currentData } = state
return {
[ACTIONS.REQUEST]: {
...INITIAL_STATE,
status: STATUS.PENDING,
data: currentData,
[reload ? 'reloading' : 'loading']: true
},
[ACTIONS.SUCCESS]: {
@ -39,12 +41,13 @@ const fetchReducer = (state, action) => {
[ACTIONS.FAILURE]: {
...INITIAL_STATE,
status: STATUS.ERROR,
data: currentData,
error: payload
}
}[type] ?? state
}
const useFetch = request => {
const useFetch = (request, socket) => {
const cancelRequest = useRef(false)
const [state, dispatch] = useReducer(fetchReducer, INITIAL_STATE)
@ -54,6 +57,18 @@ const useFetch = request => {
}
}, [])
useEffect(() => {
const isFetched = state.data !== undefined && state.status === STATUS.FETCHED
isFetched && socket?.connect(
socketData => dispatch({ type: ACTIONS.SUCCESS, payload: socketData })
)
return () => {
socket?.disconnect()
}
}, [state.data, state.status])
const doFetch = useCallback(async (payload, reload = false) => {
dispatch({ type: ACTIONS.REQUEST, reload })