Twitter_Clone(4)

한상현·2021년 2월 12일
0

React_Project

목록 보기
4/4
post-thumbnail

😀 Tweets 기능을 만들어봤으니 이제는 Profile 기능을 만들어봅니다.

📌 Get My Tweets

💻 Profile.js

const Profile = ({userObj}) =>{
    ...
    const getMyTweet = async() =>{
        const tweets = await dbService.collection("tweets").where("creatorID","==",userObj.uid).orderBy("creatorAt").get(); 
        tweets.docs.map(doc => doc.data());
    }
    useEffect(() =>{
        getMyTweet();
    },[])
    return( ... )
}

📌 코드 설명

  1. Router에서 보내준 userObj props로 받아옴.
  2. where : 필터링하는 방법
    • orderby를 만드려면 index 생성해야함.
    • 정렬 (기준, 오름차순, 내림차순)
  3. useEffect에서 사용.

📌 Update Profile

💻 Profile.js
const Profile = ({userObj}) =>{
    const history = useHistory();
    const [newDisplayName, setNewDisplayName] = useState(userObj.displayName);
  ...
const onChange = (e) =>{
        const{
            target:{value}
        } = e;
        setNewDisplayName(value);
    }
 const onSubmit = async(e) =>{
     e.preventDefault();
     if(userObj.displayName !==newDisplayName){
         await userObj.updateProfile({
             displayName: newDisplayName,
         })
     }
 }

📌 코드 설명

  1. newDisplayName의 default 값은 userObj.displayName
  2. onSubmit
    • newDisplayName에 설정된 값과 userObj.displayName이 다르면(Update를 진행했으면) if문 성립.
    • updateProfile로 DisplayName을 바꿔줄 수 있음.
    • updateProfile의 변수에는 photoProfile도 존재. PhotoURL을 넣어줄 수도 있음.

🧨 But, input에 새로운 userName을 넣어주고 submit을 해줬을 때, 바로 바뀌지 않음.

📌 Update Profile Bugfix

💻 App.js
const refreshUser = () => {
      setUserObj(autoService.currentUser)
      }); 
    }  
💻 Profile.js
const onSubmit = async(e) =>{
        e.preventDefault();
        if(userObj.displayName !==newDisplayName){
            await userObj.updateProfile({
                displayName: newDisplayName,
            })
        };
        refreshUser();
    }

📌 코드 설명

  1. App.js에서 UserObject를 관리.
    • 그러므로 refreshUser 함수를 App.js에서 선언해준 뒤, 필요한 곳으로 전파.
  2. Submit이 진행되었을 때, refreshUser() 함수를 불러주어, UserObj를 바꾸고 rerendering 진행한다는 의미.
  3. 🧨But, 실시간으로 UserName이 바뀌지 않음.

👀Why??

  • UserObject는 상당히 큰 객체.
  • 우리는 이 큰 객체에서 UserName만 바꿔줄 것.
  • React에서는 차이를 느끼지 못하여 reredering이 되지 않는 것.
  • 그러므로 Object에서 필요한 부분만 빼온다.
💻App.js
useEffect(() =>{
    authService.onAuthStateChanged((user) => {
      if(user){
        setIsLoggedIn(true);
        setUserObject({
          displayName:user.displayName,
          uid:user.uid,
          updateProfile: (args) => user.updateProfile(args),
        });
      } 
      ...
    }, []);
      
const refreshUser = () => {
      const user = authService.currentUser;
      setUserObject({
        displayName:user.displayName,
        uid:user.uid,
        updateProfile: (args) => user.updateProfile(args),
      }); 
    }  

📌 코드 설명

  1. 전체 코드에서 사용하는 displayName, uid, updateProfile만 빼옴.
  2. Object가 작아지기에 React에서 변화를 빠르게 눈치채고 바뀌는 즉시 Update.

<참고 : 노마드 코더>

profile
의 공부 노트.

0개의 댓글

관련 채용 정보