-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor #202 : 영수증 명언 상태관리를 useReducer를 이용한 훅으로 변경
상태에 따라 나타나는 명언을 더 쉽게 컨트롤하기 위해 변경했습니다.
- Loading branch information
Showing
2 changed files
with
65 additions
and
12 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
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,54 @@ | ||
// 참고 자료 - https://react.vlpt.us/integrate-api/03-useAsync.html | ||
|
||
import { useReducer, useEffect } from "react"; | ||
|
||
function reducer(state, action) { | ||
switch (action.type) { | ||
case "LOADING": | ||
return { | ||
loading: true, | ||
data: null, | ||
error: null, | ||
}; | ||
case "SUCCESS": | ||
return { | ||
loading: false, | ||
data: action.data, | ||
error: null, | ||
}; | ||
case "ERROR": | ||
return { | ||
loading: false, | ||
data: null, | ||
error: action.error, | ||
}; | ||
default: | ||
throw new Error(`Unhandled action type: ${action.type}`); | ||
} | ||
} | ||
|
||
function useAsync(callback, deps = []) { | ||
const [state, dispatch] = useReducer(reducer, { | ||
loading: false, | ||
data: null, | ||
error: false, | ||
}); | ||
|
||
const fetchData = async () => { | ||
dispatch({ type: "LOADING" }); | ||
try { | ||
const data = await callback(); | ||
dispatch({ type: "SUCCESS", data }); | ||
} catch (e) { | ||
dispatch({ type: "ERROR", error: e }); | ||
} | ||
}; | ||
|
||
useEffect(() => { | ||
fetchData(); | ||
}, deps); | ||
|
||
return [state, fetchData]; | ||
} | ||
|
||
export default useAsync; |