인프런 커뮤니티 질문&답변

나황제님의 프로필 이미지

작성한 질문수

[코드팩토리] [중급] Flutter 진짜 실전! 상태관리, 캐시관리, Code Generation, GoRouter, 인증로직 등 중수가 되기 위한 필수 스킬들!

Restaurant Pagination - 5

paginate() 에 대한 질문입니다.

24.10.17 18:12 작성

·

42

·

수정됨

0

   void paginate({
    int fetchCount = 20,
    // 추가로 데이터 더 가져오기
    // true = 더 가져오기
    // false = 새로고침
    bool fetchMore = false,
    // 강제로 다시 로딩하기
    // true - CursorPaginationLoading()
    bool forceRefetch = false,
  }) async {
    // 5가지 가능성
    // State의 상태
    // 1) CursorPagination - 정상적으로 데이터가 있는 상태
    // 2) CursorPaginationLoading - 데이터 로딩중(현재 캐시 없음
    // 3) CursorPaginationError = 에러가 있는 상태
    // 4) CursorPaginationRefetching = 첫번째 페이지부터 다시 데이터를 가져올때
    // 5) CursorPaginationFetchMore - 추가 데이터를 paginate 해오라는 요청을 받았을때

    // 바로 반환하는 상황
    // 1) hasMore == false(기존 상태에서 이미 다음 데이터가 없다는 값을 들고 있다면)
    // 2) 로딩중 - fetchMore : true
    //     fetchMore : false  - 새로고침의 의도가 있음.
    try {
      if (state is CursorPagination && !forceRefetch) {
        final pState = state as CursorPagination;

        if (!pState.meta.hasMore) {
          return;
        }
      }
      final isLoading = state is CursorPaginationLoading;
      final isRefetching = state is CursorPaginationRefetching;
      final isFetchingMore = state is CursorPaginationFetchingMore;

      if (fetchMore && (isLoading || isRefetching || isFetchingMore)) {
        return;
      }

      // PaginationParams 생성
      PaginationParams paginationParams = PaginationParams(
        count: fetchCount,
      );

      // fetchMore
      if (fetchMore) {
        final pState = state as CursorPagination;

        state = CursorPaginationFetchingMore(
          meta: pState.meta,
          data: pState.data,
        );

        paginationParams = paginationParams.copyWith(
          after: pState.data.last.id,
        );
      }


      final resp = await repository.paginate(
        paginationParams: paginationParams,
      );

      if (state is CursorPaginationFetchingMore) {
        final pState = state as CursorPaginationFetchingMore;

        // 기존 데이터에 새로운 데이터 추가
        state = resp.copyWith(data: [
          ...pState.data,
          ...resp.data,
        ]);
      } else {
        state = resp;
      }
    } catch (e) {
      state = CursorPaginationError(message: '데이터를 가져오지 못했습니다.');
    }
  }

이부분이 있는데

왜 하위의 fetchMore의 else문에서 또 조건을 걸어놓는지 궁금합니다.

  // fetchMore
        if (fetchMore) {
          final pState = state as CursorPagination;

          state = CursorPaginationFetchingMore(
            meta: pState.meta,
            data: pState.data,
          );

          paginationParams = paginationParams.copyWith(
            after: pState.data.last.id,
          );
        }
        // 데이터를 처음부터 가져오는 상황
        else {
          // 만약 데이터가 있는 상황이라면 기존 데이터 보존한 채로 Fetch(API 요청)을 진행
          if (state is CursorPagination && !forceRefetch) {
            final pState = state as CursorPagination;

            state = CursorPaginationRefetching(
              meta: pState.meta,
              data: pState.data,
            );
          } else {
            state = CursorPaginationLoading();
          }
        }

답변 2

0

코드팩토리님의 프로필 이미지
코드팩토리
지식공유자

2024. 10. 18. 14:26

안녕하세요!

이제보니 굳이 필요없는 조건문 같습니다.

완전히 중복이네요.

감사합니다!

0

인프런 AI 인턴님의 프로필 이미지

2024. 10. 17. 18:16

안녕하세요, 인프런 AI 인턴입니다. 나황제님.

질문 내용에서 fetchMoreelse문에 대해 궁금하신 부분은 다음과 같은 이유로 설명드릴 수 있습니다.

우선, paginate 함수에서 정의한 상태들은 CursorPagination, CursorPaginationLoading, CursorPaginationError, CursorPaginationRefetching, CursorPaginationFetchingMore 입니다. 각각의 상태는 데이터를 어떻게 가져오는지에 대한 다섯 가지 시나리오를 설명한 것입니다.

fetchMoretrue인 경우, 이는 사용자가 현재 페이지에 더 많은 데이터를 추가로 가져오고 싶다는 것을 나타냅니다. 이 경우, 기존의 데이터를 그대로 유지하면서 “추가로” 데이터를 가져와야 하므로 CursorPaginationFetchingMore 상태로 변환하여 로딩을 진행합니다.

fetchMorefalse인 경우에는 두 가지 하위 경우의 수가 있습니다.
1. 데이터가 이미 존재하는지에 따라 CursorPaginationRefetching 또는 CursorPaginationLoading 상태로 변경됩니다.
- 데이터가 존재하고(상태가 CursorPagination인 경우) 강제 갱신하지 않는 경우, CursorPaginationRefetching 상태로 변경하여 기존 데이터를 보존하며 데이터를 갱신합니다. 이는 사용자의 갱신 의도를 반영하기 위한 것입니다.
- 데이터가 없거나 강제 갱신하는 경우, 새로운 데이터를 가져오는 상태로 전환하기 위해 CursorPaginationLoading 상태로 변경됩니다.

각 조건문은 상태에 따라 다른 로직으로 데이터를 가져와야 하기 때문에 이러한 구조를 사용하게 됩니다. 이는 사용자가 원하는 데이터를 어떻게 잘 보여줄 수 있을지를 결정합니다.

다음 URL을 참조하시면 유사한 질문과 답변을 확인하실 수 있습니다:
- CursorPaginationRefetching 상황은 구현인 안된건가요??
- Restaurant Pagination의 provider 로직관련입니다.

저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다.
현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏
추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.

나황제님의 프로필 이미지
나황제
질문자

2024. 10. 18. 07:47

위에서 이미 해당 조건으로 통과했는데 하위에서 또 그조건을 물어보는게 이상하잖슴니까