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

[FE] local storage의 CurrentFloor 값이 없을 때 발생하는 TypeError 에러 수정 #1727 #1728

Open
wants to merge 21 commits into
base: dev
Choose a base branch
from

Conversation

jnkeniaem
Copy link
Collaborator

@jnkeniaem jnkeniaem commented Feb 10, 2025

해당 사항 (중복 선택)

  • FEAT : 새로운 기능 추가 및 개선
  • FIX : 기존 기능 수정 및 정상 동작을 위한 간단한 추가, 수정사항
  • BUG : 버그 수정
  • REFACTOR : 결과의 변경 없이 코드의 구조를 재조정
  • TEST : 테스트 코드 추가
  • DOCS : 코드가 아닌 문서를 수정한 경우
  • REMOVE : 파일을 삭제하는 작업만 수행
  • RENAME : 파일 또는 폴더명을 수정하거나 위치(경로)를 변경
  • ETC : 이외에 다른 경우 - 어떠한 사항인지 작성해주세요.

설명

더 자세한 내용은 트러블 슈팅 문서를 참고하세요

문제

before.mov
Cannot read properties of undefined (reading 'toString')

센트리를 통해 currentFloorundefined일때 toString을 호출 시 발생하는 에러임을 확인.

export const currentFloorNumberState = atom<number>({
  key: "CurrentFloor",
  default: undefined, //
  effects_UNSTABLE: [persistAtom],
});

atom 정의부 확인하니 초기값이 undefined로 설정돼있음.

원인

로컬스토리지에 currentFloor 값이 없는채로 페이지를 새로고침하면 recoil의 상태도 함께 초기화됨. 따라서 currentFloor는 undefined(초기값)가 됨.

해결

export const currentFloorNumberState = atom<number>({
  key: "CurrentFloor",
  default: 0, //
  effects_UNSTABLE: [persistAtom],
});

초기값을 0으로 변경

after.mov

로컬스토리지에 값 없을 시 /home으로 이동

리팩토링

  • currentFloorNumberState 변수명 통일

    현재 currentFloorNumberState를 여러 파일에서 currentFloorNumber, currentFloor, floor 같이 다양하게 선언해서 사용 중.

    이렇게 같은 state를 다른 변수명으로 사용 시 단점

    • 유지보수 시 불필요한 혼란을 초래할 수 있음 → 코드 파악 시간 길어짐
    • 변수명이 다르면 검색 시 놓칠 가능성이 높음.

    대표적으로 위와 같은 단점이 있기에 효율을 높이고 실수를 방지하기 위해 변수명을 currentFloor로 통일하게 됨.

    const currentFloor = useRecoilValue<number>(currentFloorNumberState);
  • useRecoilState vs useRecoilValue - value 밖에 안쓰면 useRecoilValue로 변경

    const [currentFloor] = useRecoilState<number>(currentFloorNumberState);
    const currentFloor = useRecoilValue<number>(currentFloorNumberState);
    • useRecoilValue
      • 상태 값만 반환
    • useRecoilState
      • 상태 값을 반환할 뿐만 아니라 상태를 변경할 수 있는 setter 업데이트 함수가 생성되고 반환. 읽기만 필요한 경우 불필요하게 setter 함수가 생성돼서 메모리에 로드되므로 메모리 낭비가 발생.

    미미하지만 유효한 차이가 있기 때문에, currentFloor를 선언할 때 value만 사용하는 경우에는 useRecoilState 대신 useRecoilValue로 변경함.

이 외의 코드 변경

  • 0으로 초기화한 후 새로고침 했을때 /home으로 이동하기 전에 MainPage 컴포넌트가 잠깐 보이는 이슈 발생

    해결 : 삼항 연산자를 사용하여 로딩 끝난 후 currentFloor 없으면 바로 홈페이지로 이동되도록 로직 수정

👉🏻 currentFloor가 undefined가 되는 추가적인 경우가 있다면 알려주세요 👈🏻

그리고 더 좋은 해결 방법이나 의견 있으면 편하게 코멘트 달아주세요 !

#1727

saewoo1 and others added 18 commits October 25, 2024 19:33
[FE] ETC: Sentry traces sample, error replay sample 비율 상향 #1709
…to fe/dev/fix_currentFloor_undefined_type_error/#1727
@jnkeniaem jnkeniaem self-assigned this Feb 10, 2025
@jnkeniaem jnkeniaem changed the title Fe/dev/fix current floor undefined type error/#1727 [FE] local storage의 CurrentFloor 값이 없을 때 발생하는 TypeError 에러 수정 #1727 Feb 10, 2025
@jnkeniaem jnkeniaem marked this pull request as ready for review February 10, 2025 09:07
Copy link
Collaborator

@wet6123 wet6123 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

고생하셨습니다~

frontend/src/Cabinet/pages/MainPage.tsx Outdated Show resolved Hide resolved
frontend/src/Cabinet/recoil/selectors.ts Outdated Show resolved Hide resolved
Copy link
Collaborator

@jihyunk03 jihyunk03 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

요즘 센트리 알림이 계속 왔었는데 이 이유 때문이었군요! 상세한 설명 감사합니다!!

@gykoh42 gykoh42 self-requested a review February 12, 2025 05:17
Copy link
Collaborator

@gykoh42 gykoh42 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

저번에 해당 에러를 어떻게 처리하면 좋을지 같이 구두로 이야기 나눠보았던것 같은데 잘 마무리 지으셨군요! 센트리 알림이 종종 오길래 신경쓰였는데 해결되어 다행입니다. 고생 많으셨습니당👍👍

Copy link
Collaborator

@jimchoi9 jimchoi9 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

센트리를 이용해 이런식으로 에러 추적을 하는군요.. 많이 배워갑니다! 변수명 통일하는 부분도 잘 숙지하도록 하겠습니다 pr을 상세히 적어주신 덕분에 아직 잘 모르는 부분들도 이해가 훨씬 수월했습니다! 고생 많으셨어요!

@wet6123
Copy link
Collaborator

wet6123 commented Feb 15, 2025

TypeScript의 타입 체크는 컴파일 타임에만 동작하고 런타임에서는 사라지기 때문에, 실제 실행 중에 값이 undefined인지 확인해야하는 경우가 있어요. currentFloor에 대한 런타임 체크가 존재하지 않아서 undefined인 경우에 toString메서드를 실행하려고 해서 문제가 발생했던 것 같습니다.
따라서 currentFloorNumberState의 기본 값을 0으로 바꾸는 대신 undefined에 대한 명시적인 처리를 추가하면 더 좋았을 것 같습니다. currentFloor.toString()을 옵셔널 체이닝으로 처리하거나, currentFloor 사용 전에 typeof currentFloor === 'undefined'으로 확인해서 풀백 처리하면 처리할 수 있었을 것 같아요.

추가적으로 궁금한 부분이 있는데 에러 발생 시 메인 페이지로 보내는 것은 어디서 처리되는건가요? 생각보다 찾기가 힘드네요.

@jnkeniaem
Copy link
Collaborator Author

jnkeniaem commented Feb 18, 2025

TypeScript의 타입 체크는 컴파일 타임에만 동작하고 런타임에서는 사라지기 때문에, 실제 실행 중에 값이 undefined인지 확인해야하는 경우가 있어요. currentFloor에 대한 런타임 체크가 존재하지 않아서 undefined인 경우에 toString메서드를 실행하려고 해서 문제가 발생했던 것 같습니다. 따라서 currentFloorNumberState의 기본 값을 0으로 바꾸는 대신 undefined에 대한 명시적인 처리를 추가하면 더 좋았을 것 같습니다. currentFloor.toString()을 옵셔널 체이닝으로 처리하거나, currentFloor 사용 전에 typeof currentFloor === 'undefined'으로 확인해서 풀백 처리하면 처리할 수 있었을 것 같아요.

트러블 슈팅 문서 - 초깃값 변경 고민에 작성했듯이 undefined로 유지할까도 생각했는데요,
현재 대부분의 경우 currentFloor를 number | undefined가 아닌 number 타입으로 지정해서 사용하기 때문에 변경해야하는 코드 양이 많아 일일이 변경하는 것이 비효율적인것같고,
이 변수가 숫자를 저장해서 undefined로 유지하는 것의 큰 장점이 없어보여서 0으로 바꿨는데,
그래도 undefined로 하는게 더 나을까요 ?

@jnkeniaem
Copy link
Collaborator Author

추가적으로 궁금한 부분이 있는데 에러 발생 시 메인 페이지로 보내는 것은 어디서 처리되는건가요? 생각보다 찾기가 힘드네요.

메인 페이지로 보내는 등의 처리는 따로 안했고, 에러가 발생하면 센트리가 자동으로 에러가 발생한 경로 및 파일 등을 수집해서 기록합니다.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

8 participants