Skip to content

Conversation

@Ospac
Copy link
Collaborator

@Ospac Ospac commented Sep 7, 2025

#️⃣ Related Issue

ex) #이슈번호, closed #이슈번호

📝 Problem

  • dashboard-header API 연동
  • side-menu API 연동 및 페이지네이션 기능
  • modal z-index 이슈
  • API 요청시 zod 데이터 형식 문제

✅ Solving

  • API 연동
    • zod 데이터 형식 fix ✅
    • CSR 데이터 페칭을 간편하게 하는 useAsync, useFetch, useMutate를 정의
      • dashboard-header API 연동 ✅
      • side-menu API 연동 ✅
  • modal z-index 이슈 -> Portal 컴포넌트를 정의해서 해결 ✅ (참고자료: 내가 Modal을 구현하는 방법 with Next.js, portal)

📚 Attachment

useAsync, useFetch, useMutate

useAsync (ts 없는 버전)

useAsync는 data, loading, error 상태를 관리하는 훅입니다.
기존에는 useRef가 없는 조금 단순한 형태였는데, 이전에 멘토님의 조언을 반영함에 따라서 좀 복잡한 형태가 되었습니다.

이 훅을 직접 실행할 일은 없고, useFetch, useMutate를 호출하여 사용합니다.

export default function useAsync({
  asyncFunction,
  deps = [],
  immediate = false,
}: useFetchParams) {
  const [state, setState] = useState({
    data: null,
    loading: false,
    error: null,
  });

  const asyncFnRef = useRef(asyncFunction);

  useEffect(() => {
    asyncFnRef.current = asyncFunction;
  }, [asyncFunction]);

  const refetchRef = useRef(null);

  if (refetchRef.current === null) {
    refetchRef.current = async () => {
      setState((prev) => ({ ...prev, error: null, loading: true }));
      try {
        const response = await asyncFnRef.current();

        setState((prev) => ({ ...prev, loading: false, data: response }));
      } catch (error) {
        if (error instanceof Error) {
          setState({ data: null, loading: false, error });
        }
      }
    };
  }

  useEffect(() => {
    if (refetchRef.current === null) {
      return;
    }
    if (immediate) {
      refetchRef.current();
    }
  }, [immediate, ...deps]);

  return { ...state, refetch: refetchRef.current };
}

useFetch

GET을 위한 훅입니다.

immediate (default = true)를 넣어 즉시 fetch를 실행하거나 실행하지 않을 수 있고,
deps를 넣어 refetch 조건을 만들 수 있습니다.

  1. 다음과 같이 간단히 사용하거나,
const { data, loading, error } = useFetch({
    asyncFunction: () => getMyInfo(),
  });
  1. 의존 배열을 넣어서 variable1, 2가 변하면 refetch 되는 형태
const { data, loading, error } = useFetch({
    asyncFunction: () => getMyInfo(),
    deps: [variable1, variable2]
  });

3. 상황에 따라 그냥 useEffect를 추가하여 refetch를 할수도 있겠습니다..

```tsx
 const { data: dashboardData, refetch } = useFetch({
    asyncFunction: () => getDashBoard(Number(dashboardId)),
    immediate: false,
  });

  useEffect(() => {
    if (dashboardId) {
      refetch();
    }
  }, [dashboardId, refetch]);

useMutate

PUT, POST, DELETE를 위한 훅입니다.
기본적으로 즉시 fetch가 되지 않으며, mutate를 호출하면 fetch가 됩니다.

다음과 같이 사용합니다!

const { data, loading, error, mutate } = useMutate({
    asyncFunction: () => createDashBoard(formData),
  });

@Ospac Ospac self-assigned this Sep 7, 2025
@vercel
Copy link

vercel bot commented Sep 7, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Comments Updated (UTC)
taskify Ready Ready Preview Comment Sep 7, 2025 3:01pm

@Ospac Ospac added the ⚙️ 환경 개발 환경 세팅 label Sep 7, 2025
@Ospac Ospac added this to the 기능 구현 및 1차 마무리 milestone Sep 7, 2025
@Ospac Ospac added ✨ 기능 기능 구현 and removed ⚙️ 환경 개발 환경 세팅 labels Sep 7, 2025
@Ospac Ospac merged commit 2f53e20 into develop Sep 8, 2025
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

✨ 기능 기능 구현

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants