프리온 보딩 배운 내용 정리

Imnottired·2023년 3월 19일
0

CORS 무시모드로 크롬 실행

  1. 크롬 바로가기 새로 만들어주세요
  2. 바로가기에서 마우스 우클릭 ⇒ [속성]을 클릭하세요
  3. 대상에 아래 내용 추가하시고,

--disable-web-security --user-data-dir="C:\chrome”

  1. [적용] 눌러서 저장해주세요.
  2. 해당 바로가기로 크롬 실행하시고, 진행해보세요 🙂

위 대상에 추가해주면 된다.

Credentials 옵션으로 쿠키 보내기

fetch("https://example.com:1234/users/login", {
method: "POST",
credentials: "include", // 클라이언트와 서버가 통신할때 쿠키 값을 공유하겠다는 설정
})

https://inpa.tistory.com/entry/AXIOS-%F0%9F%93%9A-CORS-%EC%BF%A0%ED%82%A4-%EC%A0%84%EC%86%A1withCredentials-%EC%98%B5%EC%85%98#withcredentials_%EC%98%B5%EC%85%98%EC%9C%BC%EB%A1%9C_%EC%BF%A0%ED%82%A4_%EB%B3%B4%EB%82%B4%EA%B8%B0

reduce로 배열만드는 활용법

export const SidebarContent: SidebarElement[] = routerData.reduce(
  (prev: SidebarElement[], router: RouterElement) => {
    if (router.withAuth) return prev;
    return [
      ...prev,
      {
        id: router.id,
        path: router.path,
        label: router.label,
      },
    ];
  },
  [] as SidebarElement[]
);

라우터를 생성맵

맵을 사용하여서 라우터에 넘겨줄 때 상황에 맞게 전처리 과정을 넣었는데 인상적이었다.

현재 위치와 라우터 변경 훅

import { useNavigate } from 'react-router-dom'

export const useRouter = () => {
  const router = useNavigate()

  return {
    currentPath: window.location.pathname,
    routeTo: (path: string) => router(path)
  }
}

  const { currentPath, routeTo } = useRouter();

라우터 훅

extends 활용

상황에 맞는 Type 설정을 위하여

interface RouterBase {
  id: number // 페이지 아이디 (반복문용 고유값)
  path: string // 페이지 경로
  label: string // 사이드바에 표시할 페이지 이름
  element: React.ReactNode // 페이지 엘리먼트
}

interface UserAccessibleRouterElement extends RouterBase {
  withAuth?: boolean // 인증이 필요한 페이지 여부
}

interface AdminAccessibleRouterElement extends RouterBase {
  withAuth: true // 인증이 필요한 페이지 여부
  isAdminPage?: boolean // 어드민 페이지 여부
}

extends를 활용하고 두개의 타입을 주었다.

&& 연산자 활용

isAdminPage={"isAdminPage" in router && router.isAdminPage}

router 키값이 isAdminPage가 존재하고 그 값이 트루일 때라는 조건을
연산자를 활용한 한줄로 표현하였음

includes 활용

이를 활용하여 값이 있는지 확인하였음
값이 있는지 없는지 확인 도와줌

const array1 = [1, 2, 3];

console.log(array1.includes(2));
// Expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// Expected output: true

console.log(pets.includes('at'));
// Expected output: false

state-> useRef 사용으로 렌더링 없이 사용

  const isUserItemsFetched = useRef(false);

  // TODO 4-2: getItems를 호출하여 userItem을 가져온 경우 상태 업데이트
  const fetchUserItems = useCallback(async () => {
    const userItems = await getItems();

    if (userItems !== null) setItems(userItems);

    isUserItemsFetched.current = true;
  }, []);

  useEffect(() => {
    if (!isUserItemsFetched.current) fetchUserItems();//렌더링없이 가능
  }, []);
  

fetch를 상황에 맞는 함수로 처리함

fetch를 감싸주면서 좀 더 통제 가능한 fetch 함수로 거듭남

export const getAllItems = async (): Promise<Item[] | null> => {
const itemRES = await fetch(`${BASE_URL}/all-items`, {
  method: "GET",
  headers: {
    "Content-Type": "application/json",
    credentails: "includes",
  },
});

return itemRES.ok ? itemRES.json() : null;
};
profile
많이 배우려고 하고 합니다. 아쉬운 점이 있으면 말씀해주시면 감사하겠습니다.

0개의 댓글