sns 프로젝트

트위터 팔로우 기능 구현하기(React, CSS hover기능)

우주속공간 2024. 1. 22. 21:44

 

구현한 기능


  • following 클릭하면 follow 로 바꾸기
  • 팔로우중일 경우, 버튼 위에 마우스를 올렸을때 다른 css주기

 

구현 과정


  1. 데이터베이스에 follow 테이블 생성 & user table과 관계 형성
  2. follow 데이터를 저장하는 saveFollow API 코드 생성
  3. 데이터를 가져오는 getTweets파일 수정 
    ⇒ explore페이지의 people데이터를 가져올때, 데이터 중에서 현재 로그인한 currentUser가 팔로우한 유저의 데이터가 있으면 is_follow값을 true값으로 반환(기본값은 false)
  4. 팔로우 버튼 css 수정

 

백엔드 saveFollow 코드

 

현재 로그인한 사용자의 이메일 아이디를 통해 유저 id를 찾고 팔로우할 유저와 현재 로그인 유저 데이터를 follow model에 저장

router.post(
  "/",
  verifyAccessToken,
  verifyRefreshToken,
  async (req: any, res: Response, next: NextFunction) => {
    const currentUser: Users[] = await Users.findOne({
      where: {
        email: req.email,
      },
    }).then((r: any) => {
      return r.user_id;
    });

    await Follow.create({
      user_id: req.body.user_id,
      follower_id: currentUser,
    }).then((result) => {
      res.status(201).json(result);
    });
  }
);

router.post(
  "/delete",
  verifyAccessToken,
  verifyRefreshToken,
  async (req: any, res: Response, next: NextFunction) => {
    const currentUser: Users[] = await Users.findOne({
      where: {
        email: req.email,
      },
    }).then((r: any) => {
      return r.user_id;
    });

    await Follow.destroy({
      where: {
        user_id: req.body.user_id,
        follower_id: currentUser,
      },
    }).then((result) => {
      res.status(201).json(result);
    });
  }
);

 

 

그리고 people 데이터를 가져오는 API에서 is_follow 변수로 현재 로그인한 유저가 해당 유저를 팔로잉했는지 구별

 let is_follow = false;
        if (
          d.follow.some((i: any) => {
            return i.follower_id === currentUser;
          })
        ) {
          is_follow = true;
        }

 

프론트 Follow 버튼 코드, css 파일

=> following 유무에 따라서 다른 함수와 다른 버튼 보여주기

<div className=" followBox">
                      <button
                        className=""
                        key={t.user_id}
                            onClick={() => {
                              t.following
                                ? deleteFollow(t.user_id)
                                : saveFollow(t.user_id);
                            }}
                          >
                        {t.following ? (
                          <div className=" ">
                            <span className="follow hover:bg-slate-800 ">
                              Following
                            </span>
                          </div>
                        ) : (
                          <>
                            <div className="following">
                              <span className="follow">Follow</span>
                            </div>
                          </>
                        )}
                      </button>
                    </div>

 

피드백 (프론트 follow버튼 코드)


🚨 onClick 안에 함수 코드가 전개되어있어서 복잡해보임 ⇒ axios요청 함수화 시키기

수정코드 - 따로 function 함수를 만들어서 사용

const saveFollow = (prop: number) => {
    customAxios
      .post("/saveFollow", {
        user_id: prop,
      })
      .then(() => {
        queryClient.invalidateQueries(["selectExploreData"]);
      });
  };

  const deleteFollow = (prop: number) => {
    customAxios
      .post("/saveFollow/delete", {
        user_id: prop,
      })
      .then(() => {
        queryClient.invalidateQueries(["selectExploreData"]);
      });
  };
  function onExploreSearch() {
    return customAxios.get(`/getTweets/${focus}`, {
      params: { search },
    });
  }

 

피드백 - 함수화 시키기

axios요청 함수화 시키기

 

Follow 버튼 css파일 - hover사용

Explore.scss

.followBox {
  width: 100%;
  display: flex;
  justify-content: right;
  padding-right: 30px;
}

.follow {
  background-color: black;
  color: white;
  width: auto;
  height: 33px;
  border-radius: 20px;
  padding: 10px;
  padding-left: 20px;
  padding-right: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: 13px;
  font-weight: bold;
}

.following:hover span {
  display: none;
}

.following:hover:before {
  content: "UnFollow";
  color: red;
  background-color: white;
  border: 1px solid red;
  width: 3em;
  height: 33px;
  border-radius: 20px;
  padding: 10px;
  padding-left: 20px;
  padding-right: 20px;
  overflow: hidden;
  font-size: 13px;
  font-weight: bold;
}

참고 사이트

텍스트 링크에 마우스 오버 시 텍스트 변경하는 방법 [CSS]

Handling Hover, Focus, and Other States - Tailwind CSS