Skip to content

Commit

Permalink
refactor #202 : 영수증 명언 상태관리를 useReducer를 이용한 훅으로 변경
Browse files Browse the repository at this point in the history
상태에 따라 나타나는 명언을 더 쉽게 컨트롤하기 위해 변경했습니다.
  • Loading branch information
jayjeong8 committed Dec 21, 2022
1 parent 9ec1e88 commit a98e95c
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 12 deletions.
23 changes: 11 additions & 12 deletions src/components/atoms/ReceiptQuotes/ReceiptQuotes.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react";
import * as S from "./ReceiptQuotes.styles";
import useAsync from "../../../hooks/useAsync";

/**
* ReceiptQuotes
Expand All @@ -10,18 +10,17 @@ import * as S from "./ReceiptQuotes.styles";
* @returns
*/
export function ReceiptQuotes() {
const [quotesState, setQuotes] = useState();
const [state] = useAsync(getQuotes, []);
const { loading, data: quote, error } = state;
console.log(quote);

useEffect(() => {
const getQuotes = async () => {
await fetch("https://api.adviceslip.com/advice")
.then((response) => response.json())
.then((data) => setQuotes(data.slip.advice))
.catch((e) => console.error(e));
};
return <S.Quotes>{loading || error ? "Well done!" : quote}</S.Quotes>;
}

getQuotes();
}, []);
async function getQuotes() {
const response = await fetch("https://api.adviceslip.com/advice").then((response) =>
response.json(),
);

return <S.Quotes>{quotesState || "Well done!"}</S.Quotes>;
return response.slip.advice;
}
54 changes: 54 additions & 0 deletions src/hooks/useAsync.jsx
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;

0 comments on commit a98e95c

Please sign in to comment.