⛵ 항해99/TIL · WIL ✏️

[TIL] 2023.10.20 - axios.put(변경사항 바로 적용시키기)

hhhhy 2023. 10. 20. 11:02

 ① useEffect 사용 : 사진 변경 바로 적용! 

  // useEffect : 렌더링되면 실행!
  useEffect(() => {
    getMyPageInfo(); // 마이페이지 정보(사진 등등) 보여주는 get 함수 실행
  }, [profileModal]); // 프로필 설정 후 모달이 닫히니까 사진이 바로 적용됨!
  
  
  // PUT : 프로필 사진 - 기본으로 설정
  const onClickDefaultProfileHandler = async () => {
    try {
      // 사진 업로드는 폼데이터로!!!!!!!!!
      const formData = new FormData();
      formData.append("updateProfileImg", defaultProfile);

      const response = await axiosInstance.put(
        "엔드포인트 URL",
        formData
      );
      console.log("기본프로필 설정", response);
      alert(response.data.msg);
      setProfileModal(false); // 모달닫기
    } catch (error) {
      console.log("error", error);
    }
  };

 

 ② spread 연산자(...) 사용 : 소개글 변경 바로 적용! 

  // useState : get으로 가져온 마이페이지 데이터(getMyPageInfo)
  const [myPageInfo, setMyPageInfo] = useState({});
  
  // PUT : 소개글 변경
  const onClickSaveAboutMeHandler = async () => {
    try {
      const response = await axiosInstance.put(
        "엔드포인트 URL",
        {
          aboutMe,
        }
      );
      console.log("소개글", response);
      alert(response.data.msg);
      setAboutMeModal(false);
      setMyPageInfo({ ...myPageInfo, aboutMe });
      // 마이페이지 소개글에 바로 적용되게!
      // myPageInfo 상태를 업데이트할 때, 기존 myPageInfo 객체의 모든 속성을 유지하면서 aboutMe 속성을 변경된 값으로 업데이트
      
    } catch (error) {
      console.log("error :", error);
    }
  };