ziglog

    Search by

    1월 4주차 기록

    January 27, 2024 • ☕️ 7 min read

    배워가기


    eslint의 guard-for-in

    for-in 루프에는 반드시 if문을 작성해야 하는 룰

    Copy
    for (key in foo) {
      doSomething(key);
    }

    for문 내부 코드에서 unexpected error가 날 수 있기 때문이다

    ex) key 값의 타입이 doSomething 함수의 인자로 들어가면 안 되는 타입인 경우

    Ref https://eslint.org/docs/latest/rules/guard-for-in

    react-router v6의 Layout Routes

    react-router v6부터 래핑한 <Route> 컴포넌트(ex. <PageRoute>)는 <Routes>의 자식 컴포넌트로 사용하지 못한다

    다음처럼 사용하거나,

    Copy
    <Route path="/wrapped" element={<Wrapped>wrapped component</Wrapped>} />`

    공식 문서에서 권장하는 방식의 Layout Routes를 사용해야 한다.

    Copy
    <Routes>
      <Route element={<PageLayout />}> {/** ⬅️ */}
        <Route path="/privacy" element={<Privacy />} />
        <Route path="/tos" element={<Tos />} />
      </Route>
      <Route path="contact-us" element={<Contact />} />
    </Routes>

    Ref https://reactrouter.com/en/main/start/concepts#layout-routes

    react router v6의 Router 종류

    react router v6에는 그냥(?) Router(ex.<BrowserRouter>로 래핑하는 방식)와 Data Router가 있다

    data router에는 다음과 같은 API가 있으며,

    위 목록 중 하나를 사용했을 때만 data API들을 사용할 수 있다.

    data router 객체 생성 후 최상단의 index.tsx에서 <RouterProvider>에 주입하여 사용한다.

    Copy
    const router = createBrowserRouter([
      {
        path: "/",
        element: <Root />,
        loader: rootLoader,
        children: [
          {
            path: "team",
            element: <Team />,
            loader: teamLoader,
          },
        ],
      },
    ]);
    
    ReactDOM.createRoot(document.getElementById("root")).render(
      <RouterProvider router={router} />
    );
    • cf) React Native에서는 아직 Data Router를 지원하지 않는다(지원 예정)

    NBSP

    • Non-Breaking Space, 줄바꿈 없는 공백
    • 유니코드 U+00A0
    • 용도
      • 브라우저가 문자열의 공백기준으로 단어 단위로 줄바꿈을 함
      • 공백이더라도 줄바꿈하지 말아야 할 경우 이 문자를 사용
      • ex) “pm 2:00”에서 공백 줄바꿈을 예방하기 위해 “pmNBSP2:00”로 사용

    RTL의 Warning: You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one 에러

    한 번에 여러 개의 동작을 수행할 수 없음을 나타낸다.

    그렇다면 act()는 언제 써야 할까?

    이미 act로 감싸져 호출되는 경우가 대부분이라 내가 직접 쓸 일이 없다.

    act() 는 함수를 인자로 받는데, 이 함수를 실행시켜서 가상의 DOM(jsdom)에 적용하는 역할을 한다. act()함수가 호출된 뒤, DOM에 반영되었다고 가정하고 그 다음 코드를 쓸 수 있게 되서 React가 브라우저에서 실행될 때와 최대한 비슷한 환경에서 테스트할 수 있다.

    💁‍♀️ render와 fireEvent등은 이미 act로 감싸져 있다!

    위 에러의 해결 방법: userEvent 를 여러번 호출할 때는 앞에 await 을 붙여줘서 다음 액션이 이전 액션이 끝나기를 기다리도록 한다!

    Ref https://flyingsquirrel.medium.com/when-should-i-use-act-in-react-testing-library-d7dd22a3340e

    타입스크립트 제네릭 유틸

    • DeepRequired<T>

      Copy
      type DeepRequired<T> = {
        [K in keyof T]-?: T[K] extends object ? DeepRequired<T[K]> : T[K]
      }
    • NestedKeyOf<T>

      Copy
      type NestedKeyOf<DataType> = {
        [Key in keyof DataType & (string | number)]: DataType[Key] extends object
          ? `${Key}` | `${Key}.${NestedKeyOf<DataType[Key]>}`
          : `${Key}`
      }[keyof DataType & (string | number)]

    크롬 vs 사파리 버튼 클릭 이벤트

    다음 button 요소를 클릭하면 콘솔 출력 결과는 어떻게 될까? 🥸

    Copy
    <button 
      type='button' 
      onFocus={() => console.log('focused')} 
      onBlur={() => console.log('blurred')}
    >
      버튼
    </button>

    결과

    • 크롬: focused, blurred 모두 찍힌다
    • 사파리: 아무것도 출력되지 않는다…

    대부분의 브라우저는 버튼 클릭 시 버튼에 focus가 가지만, Safari는 지원하지 않는다 🤷‍♀️

    Ref https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#clicking_and_focus

    이것저것 모음집


    • pnpm -C - Run as if pnpm was started in <path> instead of the current working directory. 현재 working directory가 아닌 다른 폴더에 위치한 것처럼 속여서 해당 패키지의 명령어를 실행할 수 있게 해준다.
    • 자바스크립트의 숫자 타입은 number(int, double, float등의 구분이 없다)라서, 5.0은 5가 된다. 서버에서 내려주는 값이 제대로 사용되고 있는지 주의하자.

    기타공유


    WARP

    커서를 손쉽게 이동할 수 있고, 자동완성을 넘어 AI 추천 커맨드까지 제공하는 터미널 WARP

    Ref https://www.warp.dev/c

    React Fiber 관련 자료

    동시성(concurrent)와 병렬성(parallel)을 드디어 이해하게 되었다.

    Ref

    방대한 구글의 검색엔진에서 살아남기 (구글은 어떻게 좋은 컨텐츠를 판별할까)

    ‘품질이 좋은 컨텐츠’, ‘자기 생각과 경험이 담긴 컨텐츠’가 중요하다.

    Ref https://junghyeonsu.com/posts/search-quality-evaluator-guidelines/

    마무리


    슬슬 재밌는 생각들, 일들이 생겨나고 있는 요즘이다.

    물론 내 뜻대로 안 될 때도 많지만

    걱정없이 설레보는 하루하루


    Relative Posts:

    2월 첫주차 기록

    February 3, 2024

    1월 3주차 기록

    January 19, 2024

    zigsong

    지그의 개발 블로그

    RotateLinkImg-iconRotateLinkImg-iconRotateLinkImg-icon