Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

50-fix_multiple_requests_firing_upon_thumbnail_drop #51

Merged
merged 3 commits into from
Mar 23, 2024

Conversation

Pyotato
Copy link
Owner

@Pyotato Pyotato commented Mar 23, 2024

Description & Technical Solution

  • 이전 로드메이커에서 mantine dropzone 컴포넌트를 활용해 이미지를 드롭했을 시 blob get 요청이 무수히 fire 되는 현상이 있었습니다.
image
  • 해당 문제는 아래와 같은 상황에서 반복적으로 발생했습니다. (fix_multiple_requests_firing_upon_thumbnail_drop #50)

    • 노드 드래그, 노드 상세 내용 수정
    • dropzone에 이미지 로딩 중
  • 초기 해결안 : useCallback으로 해당 이미지 컴포넌트를 감싸서, 업로드한 파일 (files)만 변경되었을 경우 함수를 재실행하도록 했습니다.

  • 이로 인해서, 여러번 요청이 발생하는 문제는 해결되었지만, 드랍존은 토글이 가능한 panel 컴포넌트의 일부로, 해당 컴포넌트 토글을 닫았을 경우, 미리보기 이미지가 사라지고, path만 저장되는 문제가 있었습니다.

  • 최종 해결안: 로컬스토리지를 활용하여, dropzone에 이미지를 드랍했을 경우 파일리더를 생성하고, 해당 이미지를 dataurl로 로컬 스토리지와 thumbnail이라는 state에 저장하고, thumbnail와 file을 useCallback의 의존성 배열에 추가하여 변경되었을 경우만 함수가 재실행되도록 했습니다.

\\ 드랍존에 이미지 드랍  로컬 스토리지에 데이터 url 저장
<Dropzone
              accept={IMAGE_MIME_TYPE}
              onDrop={(e) => {
                setFiles(e);
                const fr = new FileReader();
                fr.readAsDataURL(e[0]);
                fr.onloadend = () => {
                  const url = fr.result as string;
                  localStorage.setItem('thumbnail', url);
                  setThumbnail(url);
                };
              }}
            >
\\....
 \\ 파일 배열과 위의 드랍존에서 로컬 스토리지에 저장했던 thumbnail이 변경되었을 시에만 미리보기 변경
  const previews = useCallback(() => {
    const url = thumbnail;
    return files.map((file) => {
      const imageUrl = URL.createObjectURL(file);

      return (
        <Image
          key={`${file.name}`}
          src={url}
          alt={`${url}`}
          onLoad={() => URL.revokeObjectURL(imageUrl)}
        />
      );
    });
  }, [files, thumbnail]);
  const onSubmitRoadmap = useCallback(async () => {

  // ...중략...
 // 로드맵 생성 시 로컬 스토리지를 비워줍니다.
    await Promise.all([
      getApiResponse<undefined>({
        requestData: formData,
        apiEndpoint: `${apiRoutes.roadmapsSlash}${response}/thumbnails`,
        method: 'POST',
        headers: {
          Authorization: `Bearer ${process.env.NEXT_PUBLIC_USER_ACCESS_TOKEN}`,
        },
      }),
      getApiResponse<undefined>({
        requestData: JSON.stringify({}),
        apiEndpoint: `${apiRoutes.roadmapsSlash}${response}/join`,
        method: 'POST',
        headers: {
          Authorization: `Bearer ${process.env.NEXT_PUBLIC_USER_ACCESS_TOKEN}`,
          'Content-Type': 'application/json',
        },
      }),
      alert(`${response} 포스팅 성공!`),
      localStorage.removeItem('thumbnail'),
      router.replace(`/roadmap/post/${response}`),
    ]);
  }, [nodes, edges, files, title, description, formData, router]);

Checklist

  • I have commented my code, particularly in hard-to-understand areas.
  • Already rebased against main branch.

@Pyotato Pyotato self-assigned this Mar 23, 2024
@Pyotato Pyotato merged commit 70d3af0 into main Mar 23, 2024
2 checks passed
@Pyotato Pyotato deleted the 48-replace_alert_with_popup branch March 23, 2024 03:29
@Pyotato Pyotato restored the 48-replace_alert_with_popup branch March 23, 2024 03:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

1 participant