본문 바로가기
개인공부/메인프로젝트

suspense, lazy 적용

by 뭉지야 2023. 5. 16.
728x90
//place

//지도페이지

import React, { useState, useEffect, lazy, Suspense } from "react";
import { useNavigate } from "react-router-dom";
import axios from "axios";
import styled from "styled-components";
import { ButtonDark } from "../components/Common/Button";
// import MapComponent from "./Map";
const MapComponent = lazy(() => import("./Map"));

/*--------------------------------스타일--------------------------------*/
const TotalStyled = styled.section`
  /* border: 10px solid black; */
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f7f7f7;
`;
const PlaceContainer = styled.div`
  /* border: 5px solid black; */
  width: 100vw;
  height: 100vh;
  max-width: 1250px;
  margin-top: 150px; //호버됬을때가 150이래서 일단 150으로 설정함.
  display: flex;
  flex-direction: column;
`;

//지도부분
const MapBodyStyled = styled.div`
  /* border: 5px solid red; */
  display: flex;
  flex-direction: column;
  flex-grow: 6.5;
  justify-content: center;
  align-items: center;
`;

//지도제목
const MapArticleStyled = styled.div`
  /* border: 5px solid black; */
  margin-bottom: 80px;
  font-size: 18px;
`;

const MapBottomStyled = styled.div`
  /* border: 3px solid blue; */
  flex-grow: 1;
  display: flex;
  flex-grow: 3.5;
  justify-content: center;
  align-items: center;
  margin-bottom: 50px;
`;

interface Shopitem {
  address: string;
  choice: boolean;
  comment: string;
  lat: number;
  lng: number;
  marketId: number;
  name: string;
  phone: string;
  workTime: string;
}
/*-----------------------------------------------------------------------*/
const Place = () => {
  const [shoplist, setShoplist] = useState<Shopitem[]>([]);
  const navigate = useNavigate();

  const King = async () => {
    await axios
      .get(`${process.env.REACT_APP_API_URL}/marts`, {
        headers: {
          "Content-Type": "application/json",
          Authorization: localStorage.getItem("authToken"),
          "ngrok-skip-browser-warning": "69420", // ngrok cors 에러
        },
      })
      .then((res) => {
        // console.log(res.data.content);
        setShoplist(res.data.content);
      })
      .catch((err) => console.log(err));
  };
  useEffect(() => {
    King();
  }, []);

  return (
    <>
      <TotalStyled>
        <PlaceContainer>
          <MapBodyStyled>
            <MapArticleStyled>픽업 매장을 선택하세요</MapArticleStyled>
            {/* <MapComponent Shopitem={Shopitem} /> */}
            {/* <MapComponent shoplist={shoplist} /> */}
            <Suspense fallback={<div>loading</div>}>
              <MapComponent shoplist={shoplist} />
            </Suspense>
          </MapBodyStyled>
          <MapBottomStyled>
            <ButtonDark width="350px" height="50%" onClick={() => navigate("/cart")}>
              선택
            </ButtonDark>
          </MapBottomStyled>
        </PlaceContainer>
      </TotalStyled>
    </>
  );
};

export default Place;
//map

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

// import { markerdata } from "./MarkerData";

declare global {
  interface Window {
    kakao: any;
    closeOverlay: () => void;
  }
}
interface Shopitem {
  address: string;
  choice: boolean;
  comment: string;
  lat: number;
  lng: number;
  marketId: number;
  name: string;
  phone: string;
  workTime: string;
}
interface ShopProps {
  shoplist: Shopitem[];
}

const MapComponent = ({ shoplist }: ShopProps) => {
  // console.log(shoplist);
  useEffect(() => {
    const container = document.getElementById("map");
    const options = {
      center: new window.kakao.maps.LatLng(37.32569664033685, 127.10734442799804),
      level: 2,
    };

    const map = new window.kakao.maps.Map(container, options);

    //사용자 현재위치 정보
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function (position) {
        const lat = position.coords.latitude,
          lon = position.coords.longitude;

        const locPosition = new window.kakao.maps.LatLng(lat, lon),
          message = "<div>현재위치</div>";

        // console.log(locPosition, message); // 이게 현재위치 잡히는거다 !!!!!!!!
        displayMarker(locPosition, message);
      });
    } else {
      const locPosition = new window.kakao.maps.LatLng(37.57022168346011, 126.98314742271637), //종각역
        message = "<div>아니야</div>";

      displayMarker(locPosition, message);
    }

    function displayMarker(locPosition: any, message: any) {
      const marker = new window.kakao.maps.Marker({
        map: map,
        position: locPosition,
      });
      const iwContent = message,
        iwRemoveable = true;

      const infowindow = new window.kakao.maps.InfoWindow({
        content: iwContent,
        removable: iwRemoveable,
      });
      infowindow.open(map, marker);
      map.setCenter(locPosition);
    }
    // console.log(shoplist);

    shoplist.forEach((el: any) => {
      // console.log("ddf");
      console.log(el);
      // console.log(el.lat);
      // console.log(shoplist);
      const marker = new window.kakao.maps.Marker({
        map: map,
        position: new window.kakao.maps.LatLng(el.lat, el.lng),
      });
      const content =
        '<div className="overlayContainer" style="background-color: red;">' +
        `<div  style="color: black;" >${el.name}</div>` +
        `<div className="shopPhone">${el.phone}</div>` +
        "</div>";
      // console.log(marketlist);
      const customOverlay = new window.kakao.maps.CustomOverlay({
        content: content,
        position: new window.kakao.maps.LatLng(el.lat, el.lng),
      });
      //마우스오버하면 커스텀어레이가 생성된다.
      window.kakao.maps.event.addListener(marker, "mouseover", () => {
        customOverlay.setMap(map);
      });

      //마우스아웃하면 커스텀어레이가 없어진다.
      window.kakao.maps.event.addListener(marker, "mouseout", () => {
        customOverlay.setMap(null);
      });
    });
  }, [shoplist]);

  return <div id="map" style={{ width: "800px", height: "500px" }}></div>;
};

export default MapComponent;
728x90