TIL 34일차 MyPage 나의 글 작성 만들기 및 설정부분과 분리

KHW·2021년 10월 29일
0

TIL

목록 보기
37/39

목표

  1. 설정부분 나의 작성글과 분리
  2. 나의 작성글 코드 작성하기

1. 설정부분과 나의 작성글 분리하기

ant-design을 이용하여 틀을 짰다.

작성한 코드


const ProfileContainer = styled.div`
  display: ${(props) => (props.display ? 'block' : 'none')};
`

const SettingContainer = styled.div`
  display: ${(props) => (props.display ? 'block' : 'none')};
`

  const [isProfileShow, setIsProfileShow] = useState(true)
  const [isSettingShow, setIsSettingShow] = useState(false)

  const headerName = {
    titleName: ['프로필', '설정'],
    keyName: ['profile', 'setting'],
  }

  const clickHeaderHandler = ({ key }) => {
    if (headerName.keyName[key] === 'profile') {
      setIsSettingShow(false)
      setIsProfileShow(true)
    } else if (headerName.keyName[key] === 'setting') {
      setIsSettingShow(true)
      setIsProfileShow(false)
    }
  }
  return (
<Menu theme="dark" mode="horizontal" defaultSelectedKeys={['0']}>
        {new Array(2).fill(null).map((_, index) => {
          const key = index
          return (
            <Menu.Item
              key={key}
              onClick={clickHeaderHandler}
            >{`${headerName.titleName[key]}`}</Menu.Item>
          )
        })}
</Menu>

<ProfileContainer display={isProfileShow} className="mypage-form">
....
</ProfileContainer>

<SettingContainer display={isSettingShow}>
...
</SettingContainer>

.....

2개의 메뉴를 만들고 해당 부분을 click이벤트를 등록해주었고
값의 대상은 headerName의 titleName에서 처리했다.

위와같이 이러한 선택할 수 있는 배너가 만들어진다.
setIsProfileShowsetIsSettingShow를 통해 display를 지정할 수 있는데 각각 styled 컴포넌트를 이용해 이를 처리한다.

정리하자면 기존 첫 설정이 isProfileShow는 true , isSettingShow는 false로 defaultSelectedKeys={['0']}에 의해 브라우저에서 보기에도 isProfileShow가 선택된 것처럼 진행하였고
각가그이 container의 display에 isProfileShowisSettingShow를 넣어주고 이는 styled 에서 연결되어
display: ${(props) => (props.display ? 'block' : 'none')};
해당 처리를 하여 true false에 따라 display를 처리할 수 있다.

2. 나의 글 작성 만들기

접근방법

  1. 세션스토리지의 token 사용
  2. token을 통해 사용자 인증확인 API -> _id 획득
  3. 특정 사용자 포스트 목록 조회 API -> 필요한 포스트 내용 획득

API 사용

1. 인증 확인

사용자가 인증이 되었는지 확인합니다.

GET /auth-user

Request Header

Authorization: bearer JWT토큰

Response

User 정보

2. 특정 채널의 포스트 목록

특정 채널의 포스트 목록을 불러옵니다.

GET /posts/channel/{channelId}

Request Params

offset: Optional<Number>
limit: Optional<Number>

Response

Post[]

작성한 코드

  useEffect(() => {
    console.log('=== useEffect first ===')
    const fetchArticles = async () => {
      const { image, _id } = await GetAuthUser()
      const postData = await GetPostAuther(_id)
      console.log(image)
      setPostDataState(postData, image)
      setimageGetProps(image)
      console.log(postData)
    }
    fetchArticles()
  }, [])

...

return 

<ProfileContainer display={isProfileShow} className="mypage-form">
        {postDataState.map(({ title, image }) => {
          return (
            <Card
              style={{ width: 300 }}
              cover={
                <img
                  alt="example"
                  src={
                    image
                      ? image
                      : 'https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png'
                  }
                  width="200px"
                  height="200px"
                />
              }
            >
              <Meta title={title} />
            </Card>
          )
        })}
      </ProfileContainer>

postDataState라는 useState를 통해 처리한 배열을 순회하면서 필요한 작성된 글의 이미지와 제목을 받아 해당 부분을 렌더링 시켜주는 처리를 하여 return하는 결과를 확인할 수 있다.

profile
나의 하루를 가능한 기억하고 즐기고 후회하지말자

0개의 댓글