새소식

반응형
WEB/Next.js

[Next.js] 페이지 새로고침 여부 확인 방법 (F5)

  • -
반응형

2023-04-05


사진: Unsplash 의 Julia Kutsenko


1. 방법

 

기존에는 아래의 코드를 사용했었다. 

 

    useEffect(() => {
        if (performance.navigation.type === 1) {
          console.log('Page was refreshed');
          // Do something when page is refreshed
        }
      }, []);

 

하지만 현재 performance.navigation.type 는 deprecated 되어 다른 방안을 찾아야 했는데 아래와 같은 글을 발견했다.

 

https://stackoverflow.com/questions/58652880/what-is-the-replacement-for-performance-navigation-type-in-angu lar

 

What is the replacement for performance.navigation.type in angular?

I have this code in order to know if the page is reload by the user, unfortunately is deprecated. I want to know if angular has this approach. if (performance.navigation.type === 1) { console.l...

stackoverflow.com


위의 코드를 예로 아래와 같은 코드를 작성화면 현재 페이지가 리로드 되었는지를 확인할 수 있다. 다만 현재 프로젝트는 기본 자바스크립트가 아닌 typescript를 사용중에 있어 또다른 문제가 발생했다.

 

    useEffect(() => {
        const entries = performance.getEntriesByType("navigation")[0];
        console.log( entries.type );
      }, []);

문제는 typeScript에서는 현재 performance.getEntriesByType의 프로퍼티 "type" 값을 인식 못하고 아래와 같은 오류가 발생한다는 점이다.

 

Property 'type' does not exist on type 'PerformanceEntry'.

 

이는 entries type은 PerformanceEntry으로 인식되고 있지만 실제 entries에 담겨 있는 오브젝트는 PerformanceNavigationTiming이다. 때문에 현재 PerformanceEntry에서 포함되지 않은 필드값 type은 확인할 수 없어 위와 같은 타입에러 발생한다. 관련 오브젝트에 대한 내용은 아래 두 가지의 링크를 참고하자.

 

https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry

 

PerformanceEntry - Web APIs | MDN

The PerformanceEntry object encapsulates a single performance metric that is part of the browser's performance timeline.

developer.mozilla.org

https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming

 

PerformanceNavigationTiming - Web APIs | MDN

The PerformanceNavigationTiming interface provides methods and properties to store and retrieve metrics regarding the browser's document navigation events. For example, this interface can be used to determine how much time it takes to load or unload a docu

developer.mozilla.org


그러면 최종적으로는 어떻게 해야 할까? 이는 typescript의 Type Assertion를 사용하면 된다. 우리는 performance.getEntriesByType 가 명확히 PerformanceNavigationTiming 오브젝트를 리턴해 준다는 사실을 알고 있다. 때문에 entries 객체를 명시적으로 PerformanceNavigationTiming  타입으로 재정의 해주면 된다.

"const entriesNavigationTiming = entries as PerformanceNavigationTiming"  코드 한 줄을 추가해 주면 된다.

 

    useEffect(() => {
        const entries = performance.getEntriesByType("navigation")[0];
        const entriesNavigationTiming = entries as PerformanceNavigationTiming
        console.log( entriesNavigationTiming.type);
      }, []);

 

그러면 entriesNavigationTiming에서는 오류 없이 필드값 type을 참조할 수 있게 되며, 문제는 해결된다.

 

 


메인 이미지 출처 : 사진: UnsplashJulia Kutsenko  

 

반응형
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.