Skip to content

상세페이지에서 게시글 삭제버튼이 자신이 쓴 글이면 true 로 바꿔 화면에 보이게 하고 다른 사람의 글이면 false로 바꿔 게시글 삭제 버튼이 화면에 안보이게 하기  #49

@sinyoung12

Description

@sinyoung12

도입 이유
접속한 사용자의 게시글에만 게시글 삭제 버튼이 보이도록 하기 위해

문제 상황
버튼에 display를 변경할 수 있도록 useState를 사용해 state를 관리하고 userId를 의존성 배열로 갖는 useEffect를 사용하여 렌더링 후 버튼의 display 상태를 변경했다.
문제 코드
const [deleteBtn, setDeleteBtn] = useState(false);

useEffect(() => {
const currentUserId = localStorage.getItem("id");
if (Number(currentUserId) === Number(data?.userId)) {
setDeleteBtn(true);
}, [data?.userId]);

발생한 문제는 내가 작성한 게시글에 들어갔다 다른 사용자 게시글을 들어갔을 때 똑같이 삭제 버튼이 뜨는 문제가 있었다.
console.log(data?.userId)를 찍어보니 처음 화면이 보여질때 Undefined 값이 나온뒤 화면이 보여질때 true false 값이 나타났다.

해결방안
if문에 else {setSeletBtn(false); 를 추가해 다른 유저의 게시글을 들어갔을 때 삭제버튼이 안나오도록 했다.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions