Frontend : React Native/Axios

[ReactNative] Axios로 게시물 Post하기

0BigLife 2022. 1. 27. 16:15
728x90

이번에는 FlatList로 구현해놓은 홈뷰에 새로운 게시글을 넣어볼까 한다. 과정은 다음과 같다.

  1. HomeNavigation의 HeaderRight 버튼을 통해 모달뷰 접근
  2. 모달뷰에서 선택지를 골라서(카메라/앨범/--) UploadView 접근
  3. UploadView에서 게시글에 들어갈 새로운 이미지소스와 텍스트를 입력
  4. 상단 체크 버튼 누를 시 서버로 Post 요청
  5. 홈뷰에서 리스트 Refresh할 시, 서버로 모든 게시글 Get 요청

중간에 게시글 텍스트와 이미지소스를 제외한 데이터만 받아오는 에러가 있었는데, 타입형 문제도 아니고 뭐지? 싶어서 어제 하루종일 낑낑대다가 결국 잠들었다.. 오늘 일어나서 터미널창 끄고 시뮬레이터도 다시 실행했더니 해결.. (네?..)

무튼 nodejs 코드는 다음을 추가했다.

//뉴스피드 가져오기
router.get('/api/feeds', (req, res) => {
	res.json(feeds);
});

//게시물 업로드
router.post('/api/feeds/add', (req, res) => {
	const feed = {
		id: feeds.length + 1,
		name: '0biglife',
		title: req.body.title,
		url: req.body.url,
		thumbnailUrl: req.body.thumbnailUrl,
		postTime: req.body.postTime,
	};
	feeds.push(feed);
	res.json({ ok: true, feeds: feed });
});

 body의 파라미터를 통해 값을 전달해올 것이므로 res.body.(변수명) 으로 받아와서 넣어줬다. id는 1만큼 더해서 넣어주고, name은 아직 회원가입할 때 유저가 입력할 정보들에 대한 픽스가 되지 않은 상태라 우선 내 닉네임을 넣어줬다. 

//React-Native Code
let today = new Date();
  let time = {
    year: today.getFullYear(),
    month: today.getMonth() + 1,
    date: today.getDate(),
  };
  let timeSet = `${time.year}-${time.month}-${time.date}`;

시간 값은 RN 쪽에서 Date() 함수를 써서 '연도-월-일' 로만 전달했다. 

그 다음은, UploadView 코드.

//UploadView 
  const PostingDone = () => {
    if (uri) {
      apiClient
        .post<ResponseFeed>('/feeds/add', {
          title: textInput,
          url: uri,
          thumbnailUrl: uri,
          postTime: timeSet,
        })
        .then(response => {
          console.log(response.data);
        });
      navigation.goBack();
    } else {
      Alert.alert('no ImageSource!');
    }
  };

이미지를 넣지 않은 상태로 게시물 업로드할 시 로직은 아직 넣지 않은 상태이기 때문에 알람창만 넣어줬다. 

추가 구현으로는, 위에서 말한 세부적인 로직과 서버에서 최신 업로드 순(수정 시 미포함)으로 게시물을 업데이트하는 것을 구현할 계획이다.

결과물

 


Logic 추가 구현(UploadView로 들어와있는 상태)

  1. 취소 버튼에 대한 로직
    1-1 ) 이미지 소스 or 텍스트가 추가된 상태에서 사용자에게 취소 여부 되묻기
    1-2 ) 이미지 소스 or 텍스트가 없는 상태에서 홈뷰로 이동
  2. 업로드 버튼에 대한 로직 (텍스트는 없어도 업로드 가능하도록 함)
    2-1 ) 이미지 소스가 추가된 상태에서 사용자에게 되물은 후 게시글 서버에 Post 요청.
    2-2 ) 이미지 소스가 없는 상태에서 사용자에게 되물은 후 홈뷰로 이동

코드는 다음과 같이 짰다.(모달은 props를 활용한 재사용이 가능한 컴포넌트로 구성)

import React from 'react';
import styled from 'styled-components/native';
import Modal from 'react-native-modal';

interface Props {
  modalVisible: boolean;
  setModalVisible: any;
  alertTitle: string;
  leftTitle: string;
  rightTitle: string;
  leftButton: () => void;
  rightButton: () => void;
}

const SimpleModal = (props: Props) => {
  return (
    <SafeAreaView>
      <Modal
        isVisible={props.modalVisible}
        animationInTiming={1}
        animationOutTiming={1}
        // hideModalContentWhileAnimating={true}
        onBackdropPress={() => props.setModalVisible(false)}>
        <ModalContainer>
          <ModalTitle>
            <ModalTitleText>{props.alertTitle}</ModalTitleText>
          </ModalTitle>
          <ButtonWrapper>
            <ModalButton onPress={props.leftButton}>
              <ModalButtonText>{props.leftTitle}</ModalButtonText>
            </ModalButton>
            <ModalButton onPress={props.rightButton}>
              <ModalButtonText>{props.rightTitle}</ModalButtonText>
            </ModalButton>
          </ButtonWrapper>
        </ModalContainer>
      </Modal>
    </SafeAreaView>
  );
};

export default SimpleModal;

 

취소 버튼, 업로드 버튼에 대한 로직 추가.

  const CancelLogic = () => {
    if (textInput || uri) {
      setCancelModal(true);
    } else {
      setCancelModal(false);
      navigation.goBack();
    }
  };

  const PostingDone = () => {
    if (uri) { //uri 여부 확인
      apiClient
        .post<ResponseFeed>('/feeds/add', {
          title: textInput,
          url: uri,
          thumbnailUrl: uri,
          postTime: timeSet,
        })
        .then(response => {
          console.log(response.data);
        });
      navigation.goBack();
    } else {
      setPostModal(false);
      Alert.alert('사진이 있어야 게시 가능합니다.');
    }
  };

 

728x90