yamoo9 / likelion-FEQA

질문/답변 — 프론트엔드 스쿨, 멋사
29 stars 9 forks source link

[LAB-8] 카카오 지도 API 포함 랜더링 관련 질문 #256

Closed rodwnl closed 1 year ago

rodwnl commented 1 year ago

질문 작성자

이경주

문제 상황

image 현재 메인페이지에서 상품 클릭 시

image image 상품 디테일 페이지로 이동하고 상품에 저장된 주소를 기반으로 지도위치를 보여주고 있습니다.

import React, {useEffect, useState} from "react";

const {kakao} = window;

export function ProductMap(props) {
  const [map, setMap] = useState(null);

  useEffect(() => {
    const container = document.getElementsByClassName("map")[0];
    const options = {center: new kakao.maps.LatLng(35.12, 129.1), level: 3};
    const kakaoMap = new kakao.maps.Map(container, options);
    setMap(kakaoMap);

    const geocoder = new kakao.maps.services.Geocoder();
    geocoder.addressSearch(props.address, function (result, status) {
      if (status === kakao.maps.services.Status.OK) {
        let coords = new kakao.maps.LatLng(result[0].y, result[0].x);

        let marker = new kakao.maps.Marker({
          map: kakaoMap,
          position: coords,
        });

        marker.setMap(kakaoMap);
        kakaoMap.setCenter(coords);
      }
    });
  }, []);

  return <div className="map"></div>;
}

이때 문제 세가지가 발생하는데

1) 위의 상세페이지에서 상품 더보기에 있는 상품 클릭시 내용은 바뀌지만 지도의 위치는 재렌더링이 되지 않습니다. image image 제주 특별차지도 위치의 K.K 상품을 클릭 했지만 지도는 여전히 인천 강화군 위치입니다 코드에 useEffect를 빈 배열로 주긴 했지만 param이 바뀌면서 새로 랜더링 되어야하는게 아닌가요?

2) 상세페이지에서 새로고침(f5)시 아무 페이지도 뜨지 않습니다. image 처음에는 읽어왔던 id 등 특정값을 왜 부르지 못하는지 모르겠습니다ㅠㅠ

3) 카카오 지도 API를 사용한 뒤 issue가 생성되었는데 왜 생성되었고 어떻게 해결하는 지 잘 모르겠습니다 image

프로젝트 저장소 URL

환경 정보

yamoo9 commented 1 year ago

문제 해결

질문에서 요구된 문제가 해결된 화면은 아래 영상으로 확인해보세요. 😃

https://user-images.githubusercontent.com/1850554/227931626-a05f7230-a344-411f-bb41-4d0212f24b82.mp4

답변 1. ProductMap 컴포넌트

ProductMap 컴포넌트 코드를 아래와 같이 작성합니다. (주석 참고)

import React, {useCallback, useEffect, useRef} from "react";

const {kakao} = window;

export function ProductMap(props) {

  // 카카오 맵 참조 생성
  const kakakoMapRef = useRef({});

  // 카카오 맵 그리는 함수
  const drawMap = useCallback(
    (address) => {
      const {geocoder, kakaoMap} = kakakoMapRef.current;

      geocoder.addressSearch(address, function (result, status) {
        if (status === kakao.maps.services.Status.OK) {
          let coords = new kakao.maps.LatLng(result[0].y, result[0].x);

          let marker = new kakao.maps.Marker({
            map: kakaoMap,
            position: coords,
          });

          marker.setMap(kakaoMap);
          kakaoMap.setCenter(coords);
        }
      });
    },
    [kakakoMapRef]
  );

  // 최초 마운트 시점에 카카오 맵 생성(및 참조) → 그리기
  useEffect(() => {
    const container = document.getElementsByClassName("map")[0];
    const options = {center: new kakao.maps.LatLng(35.12, 129.1), level: 3};

    kakakoMapRef.current.kakaoMap = new kakao.maps.Map(container, options);
    kakakoMapRef.current.geocoder = new kakao.maps.services.Geocoder();

    drawMap(props.address);

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // props.address가 변경되면 카카오 맵 다시 그리기
  useEffect(() => {
    console.log(props.address);
    drawMap(props.address);
  }, [drawMap, props.address]);

  return <div className="map"></div>;
}

답변 2. 추출한 상태 이름 오류

useProducts 훅에서 isLoading 상태가 아니라, isLoadingState 상태 이름으로 추출한 것 때문에 새로고침 할 때 오류가 발생한 것입니다. 이름을 올바르게 변경하면 새로고침으로 인한 렌더링 오류 문제가 해결됩니다.

image

가이드 파일

가이드 파일을 다운로드 받아 확인해보세요. 😀

src.zip

rodwnl commented 1 year ago

감사합니다 ㅠㅠ 놓치고 있는 부분을 포함해 많이 도움이 됐습니다!!!!!!!!!!!!!!!!

rodwnl commented 1 year ago

야무쌤 오늘 다시 확인해보니 기능이랑 오류는 다 해결됐는데 저는 야무쌤 동영상과 달리 여전히 issue 문제가 남아있는 데 이유가 있을까요..? image

yamoo9 commented 1 year ago

Cookie SameSite attribute 경고

아래 경고는 동일 사이트의 속성 값을 'Lax'로 변경 하라는 내용입니다.

Indicate whether to send a cookie in a cross-site request by specifying its SameSite attribute

Because a cookie’s SameSite attribute was not set or is invalid, it defaults to SameSite=Lax, which prevents the cookie from being sent in a cross-site request. This behavior protects user data from accidentally leaking to third parties and cross-site request forgery. Resolve this issue by updating the attributes of the cookie: Specify SameSite=None and Secure if the cookie should be sent in cross-site requests. This enables third-party use. Specify SameSite=Strict or SameSite=Lax if the cookie should not be sent in cross-site requests.

20년 2월 4일 공개된 Google Chrome v80부터 새로운 쿠키 정책이 적용 되어 Cookie의 SameSite 속성 기본 값이 None에서 Lax로 변경되었습니다.

사이트 간 요청 위조 및 의도하지 않은 정보 유출 등 보안 문제 해결을 위한 변화라고 합니다.

SameSite는 말 그대로 쿠키 전송에 있어 '동일한 사이트'인지 체크하는 것입니다. Cookie의 SameSite 속성은 서로 다른 도메인 간 쿠키 전송에 대한 보안을 설정합니다.

SameSite 설정 값은 Strcit, Lax, None 등 값을 가질 수 있는데, Strict는 동일 사이트에서만 쿠키 전송, Lax는 허용 사이트와 동일한 사이트만, None은 모든 사이트에서 허용 함을 의미합니다.

그래서 쿠키를 사용한다면 SameSite 속성 값을 아래와 같이 추가해야 합니다.

document.cookie = "safeCookie1=foo; SameSite=Lax"; 

보다 자세한 내용은 Cookie SameSite 설정하기 (Chrome 80 쿠키 이슈) 글을 참고하세요 😃

rodwnl commented 1 year ago

image image

useEffect안에 해당 코드를 추가했는데 여전히 issue 문제가 안사라집니다. 그리고 혹시 a parser-blocking warning은 왜 뜨고 이거 해결 방법이 있을까요..??

해당 브랜치 같이 첨부합니다. https://github.com/likelion-frontendo/likelion-saja/tree/develope

yamoo9 commented 1 year ago

@rodwnl 님 해당 오류는 Kakao API에서 쿠키를 사용할 때 document.write를 사용해서 생성했기 때문에 발생한 경고 메시지에요.

아래는 Kakao 측의 답변입니다. 이 경고는 작동과 무관하므로 정책상 대응하지 않기로 했다고 합니다. 즉, 이 경고는 @rodwnl 님의 잘못이 아니고 Kakao 측에서 무대응 하기로 했으므로 무시해야 할 듯 합니다. 🤔

(참고)

(참고)