[날씨어때]체크리스트 및 완료된 작업 요약

piper ·2023년 11월 29일
0

Project

목록 보기
1/15

로그인/로그아웃 버튼

===> useEffect와 전역관리 부분
~~토큰을 localStorage.removeItem()으로 삭제해주고 난 뒤에
화면을 jsx의 화면표시로
{isLoggin && (log out)} ,
{!isLoggin && (login)}
로그인이 되면 로그아웃버튼이 로그아웃버튼이면 로그인이 되게끔 화면에 표시해주려고 했는데
토큰을 삭제했음에도 새로고침을 하면 토큰이 그대로 저장되어있었다.
그때서야 useEffect가 필요하다는것을 알게되었다.
이유: 리액트는 코드가 최초 실행이 됐을 때 index.js를 통해 페이지를 한꺼번에 가져온다.
그랬을 때 로그아웃 버튼을 누르고
새로고침을 하면 토큰이 삭제된 상황이 아닌 최초의 토큰이 저장된 페이지가 랜더링 되는 것이다.
부작용이다. 이런 부작용을 해결하기 위해서 랜더링이 끝난 후 다시 useEffect안의 내용을 실행하게
되는 것이다. 만약 어떠한 값이 바뀌었을 때만 재랜더링을 시키고 싶다면 []의존성 배열 안에 어떠한
값이 바뀌었을 때 재랜더링 시킬 것인지 적는다. 그 중 한개만 바뀌어도 다시 랜더링이 일어난다.빈 의존성
배열은 최초 랜더링 그리고 그 이후에 useEffect가 단 한번만 일어난다는 의미이다. ~~

const Nav = () => {
  const [isLoggin, setIsLoggin] = useState(false);
  //const [isModalOpen, setIsModalOpen] = useState(false);

 
  useEffect(() => {
    const accessToken = localStorage.getItem("access_token");
    const refreshToken = localStorage.getItem("refresh_token");
    setIsLoggin(accessToken && refreshToken);
  }, []);

  const onLogOut = () => {
    console.log("로그아웃 버튼 클릭");
    localStorage.removeItem("access_token");
    localStorage.removeItem("refresh_token");
    setIsLoggin(false);
  };

useEffect 정리

useEffect(() => {
  // This runs after every render
});

useEffect(() => {
  // This runs only on mount (when the component appears)
}, []);

useEffect(() => {
  // This runs on mount *and also* if either a or b have changed since the last render
}, [a, b]);

의존성 배열 관련 예시

import { useState, useRef, useEffect } from 'react';

function VideoPlayer({ src, isPlaying }) {
  const ref = useRef(null);

  useEffect(() => {
    if (isPlaying) {
      console.log('Calling video.play()');
      ref.current.play();
    } else {
      console.log('Calling video.pause()');
      ref.current.pause();
    }
  }, []); // This causes an error

  return <video ref={ref} src={src} loop playsInline />;
}

export default function App() {
  const [isPlaying, setIsPlaying] = useState(false);
  const [text, setText] = useState('');
  return (
    <>
      <input value={text} onChange={e => setText(e.target.value)} />
      <button onClick={() => setIsPlaying(!isPlaying)}>
        {isPlaying ? 'Pause' : 'Play'}
      </button>
      <VideoPlayer
        isPlaying={isPlaying}
        src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4"
      />
    </>
  );
}

위의 코드를 실행하려면 의존성배열을 삭제하거나 의존성 배열 안에 [isPlaying]을 써주어야 한다.
버튼을 클릭할 때 이벤트가 발생하기 때문에 컴포넌트가 나타날때 함께 랜더링 되지 않아
자동으로 영상이 재생하지 않는다. 만약 의존성 배열을 아예 써주지 않는다면 모든 랜더링이 일어날때
마다 실행이 되기 때문에 버튼을 누르면 랜더링이 일어나고 영상이 재생된다.

아이디 중복체크와 통신

아이디 중복 체크는 서버에 post 통신을 보내고 백엔드 개발자가 보낸 서버로 부터의 응답이
200이라면 중복체크를 통과한것이고 409라면 이미 서버에 존재하는 아이디로 중복체크를 통과 하지
못하는 것으로 useState을 이용해 각각 true와 false를 사용하며 jsx문으로 사용자에게 결과를
알려준다.

const [isValiable, setIsValiable] = useState(false); 

const doubleCheck = async () => {
const {userId} = userInfo; 
//이때 객체리터럴인 userInfo의 값중 하나인 userId를  userInfo 객체에서 userId 값을 추출하여 //userId라는 변수에 할당하는 것이 목적. 
//참고:const { userId: newUserId } = userInfo; newUserId에 새롭게 할당된다. 

try {
 const response = await axios.post(`api adress/${userId}`, {nickName});
 if (response.status===200) {setIsValiable(true);}
 else if (response.status===409) {setIsValiable(false);}
 }
 catch(e) {console.log("중복체크 통신 실패", e)
 setIsValiable(false);}

}; 

3)통신 오류 해결 정리

이미지 서버에 전송하기

이미지를 서버로 전송할때는 배열에 담아서 전송한다. 주의할 점은 Array.from()을 통해
배열을 생성해주고 그 안에 파일을 담은 배열뭉태기가 file의 변수에 저장됐지만
서버에 보낼때는 forEach를 사용해서 하나씩 개별적으로 보내야 오류를 줄일 수 있다.

const [file, setFile] = useState([]);

const handleFile = (e) => {
try {
if(e.target.files){
const fileArray=Array.from(e.target.files); //새로운배열을 만들고 배열안에 파일담기
setFile(fileArray)
}
} catch (e) {console.log(e)}
}

const submitFile async() = > {

try {
e.preventSubmit();
const formData = new formData();
file.forEach((fileItem)=>{formData.append("file", fileItem, fileItem.name)})
; 
//각각의 파일을 formData에 붙이기 

const response= await axios.post('api',
formData,
{headers: {"content-Type" : "multipart/form-data"}}
) 

if(response.status===200){
console.log('전송성공', response)}
else {console.log ('전송실패' , response)}
}
}
catch (e){
console.log("통신실패", e)
} 
}
}; 

 return (
    <div>
      <input type="file" onChange={handleFile} multiple />
      <button onClick={submitFile}>파일 전송</button>
    </div>
  );
};

참고: Array.from()
참고:forEach(()=>{})
참고:파일전송,삭제,브라우저파일표시 예시

5)JS 디스트럭쳐링과 스레드 문법
Distructuring: unpack values into distinct variables.

const x = [1,2,3,4,5]; //[1,2,3,4,5] => to unpack values from sourced valiables.
const [y,z,...rest]  ; // x,y => distinct variables
console.log(y); //1 => unpacked
console.log(z)l //2
console.log(rest) //[3,4,5]

const obj = {
a:1,
b:2,
c:3
}

const {a,b}= obj; => into distinct variables a and b 

const a= obj.a;
const b = obj.b; 

객체를 새로운 변수 이름에 할당

const o = {
peter:42,
alive: true}; 

const {peter: age, alive:assigned}= o;

console.log(age); //42
console.log(assinged); //true

For of iteration and destructuring

const people = [
  {
    name: "Mike Smith",
    family: {
      mother: "Jane Smith",
      father: "Harry Smith",
      sister: "Samantha Smith",
    },
    age: 35,
  },
  {
    name: "Tom Jones",
    family: {
      mother: "Norah Jones",
      father: "Richard Jones",
      brother: "Howard Jones",
    },
    age: 25,
  },
];

for (const {
  name: n,
  family: { father: f },
} of people) {
  console.log(`Name: ${n}, Father: ${f}`);
}

연습
주의할점: 할당을 통해 복사한 것을 바꾸면 원본 소스도 바뀐다.
원본 소스를 바꿔도 할당을 통해 복사한 것이 바뀐다.

const 대한항공 = {
    userA: {name: 'david', flightNum: '402'},
    userB: {name: 'Kim', flightNum: '187'}, 
    userC: {name: 'Cici',  filghtNume: '800'}
  }; 
  const { userA : userId_A, userB : userId_B, userC: userId_C} = 대한항공
  const {userA:refundedUser} = 대한항공 // unpacked 대한항공.userA의 값을 into refundUser라는 변수에 할당 
  
  console.log(refundedUser); //=userA
  console.log(대한항공.userA); 

  refundedUser.name = 'chris'; 
  refundedUser.flightNum = '007';
  console.log(refundedUser); // { name: 'chris', flightNum: '007' }
  console.log(대한항공.userA); //  { name: 'chris', flightNum: '007' } 또한 변경된다. 
  console.log(대한항공);




 대한항공.userA.name = 'kardashian';

 console.log(대한항공) // {userA: { name: 'kardashian', flightNum: '007' },userB: { name: 'Kim', flightNum: '187' },userC: { name: 'Cici', filghtNume: '800' }}
 console.log(refundedUser, "원본소스를 카다시안으로 바꾼 이후"); // { name: 'kardashian', flightNum: '007' } 원본소스를 카다시안으로 바꾼 이후


 console.log(대한항공['userA']);
 console.log(대한항공.userA)코드를 입력하세요

7.computed Property Name

let key = "name";
let obj = {
  [key] : "yujuck"
}

// obj = { name: "yujuck" }
  1. 리프레쉬 토큰
  2. 소셜 로그인
  3. 모달 표시 (리덕스로 꼭)
  4. 회원가입하고 로그인을 다시 해야하나 ?

통신관련 참고 : https://velog.io/@wish/%EC%84%9C%EB%B2%84%EB%A1%9C-%EC%9D%B4%EB%AF%B8%EC%A7%80-%EB%B3%B4%EB%82%B4%EA%B8%B0

profile
연습일지

0개의 댓글