강의

멘토링

커뮤니티

인프런 커뮤니티 질문&답변

PaPillOn빠삐용님의 프로필 이미지
PaPillOn빠삐용

작성한 질문수

[리뉴얼] React로 NodeBird SNS 만들기

데이터 등록 관련해서 질문있습니다.

작성

·

165

0

항상 감사드립니다.

강의 응용해서 개인적인 웹사이트를 만들고 있는데

이렇게 동적으로 데이터 행을 여러개 만든후에

배열로 이루어진 데이터를 db로 보내려고 하는데

이상하게 첫번째 데이터만 db에 등록이 되네요.

프론트:

const onSubmit = useCallback((e) => {
    e.preventDefault();
    console.log("formData", formData);

    // 유효성: category 또는 src가 비어있을 경우 에러메시지 return

    // formData.append('src', src);
    // formData.append('category', category);
    // for (var pair of formData.entries()) {
    //   console.log(pair[0], pair[1]);
    // }

    // return (
    dispatch({
      type: UPDATE_WEBSITE_REQUEST,
      data: formData,
    })
    // )
    // formData.map(p => (
    //   dispatch({
    //     type: UPDATE_WEBSITE_REQUEST,
    //     data: p,
    //   })
    // ))
    setIsWebModalVisible(false)
  }, []);

리덕스 

export const initialState = {
  websites: [],
  updateWebsiteLoading: false,
  updateWebsiteDone: false,
  updateWebsiteError: null,
}
case UPDATE_WEBSITE_SUCCESS:
        draft.updateWebsiteLoading = false;
        draft.updateWebsiteDone = true;
        draft.websites = action.data;
        break;
case ADD_WEBSITE_TO_ME: // reducers/user에서
        draft.me.Websites = action.data;
        break;

saga

function* updateWebsite(action) {
  try {
    // result.data로 (call: 첫번째인자 함수실행, 두번째인자를 넣어서)
    const result = yield call(updateWebsiteAPI, action.data);
    // ContentType:'application/json'
    console.log(action.data);

    // id를 생성해서 post와 user리덕스 연결고리
    // 어떤 액션이 여러 리듀서의 데이터를 동시에(user, post)바꿔야한다면 여러 액션을 호출해주면 됨
    yield put({
      type: UPDATE_WEBSITE_SUCCESS,
      data: result.data,
      // 포스팅에 글 입력한 내용
    });
    yield put({
      type: ADD_WEBSITE_TO_ME,
      data: result.data.id,
    });
  } catch (err) {
    console.error(err);
    yield put({
      type: UPDATE_WEBSITE_FAILURE,
      error: err.response.data,
    });
  }
}

DB

module.exports = class Website extends Model {
  static init(sequelize) {
    return super.init({
      src: {
        type: DataTypes.STRING(200),
        allowNull: false,
      },
      // @ 카테고리: git, facebook 등
      category: {
        type: DataTypes.TEXT,
        allowNull: false,
      },
    }, {
      modelName: 'Website',
      tableName: 'websites', // 테이블명: 자동으로 소문자에 복수 붙음
      charset: 'utf8mb4',
      collate: 'utf8mb4_general_ci', // 이모티콘 저장
      sequelize,
    })
  }
  static associate(db) {
    db.Website.belongsTo(db.User)
  }
}

routes

router.post('/', isLoggedIn, async (req, res, next) => { // 주소: Website /post


  try {
    const exWeb = await Website.findOne({
      where: { UserId: req.user.id, }
    });
    if (exWeb) {
      await Website.destroy({
        where: { UserId: req.user.id, },
      })
    }
    const user = await User.findOne({ id: req.user.id, })
    const web = req.body;
    if (Array.isArray(web)) {
      const results = await Promise.all(web.map((p) => 
      Website.create({
        src: p.src, category: p.category, UserId: req.user.id
      })
      
      ));
      console.log(JSON.stringify(results));
      await user.addWebsites(results.map((v) => v[0])); // 게시글 post create에 추가
    }

    const fullInfo = await Website.findAll({
      where: { UserId: req.user.id },
      // include: [{
      //   model: User, // 게시글 작성자
      //   attributes: ['id', 'nickname'],
      // },]
    })
    // 다시 frontend로 전송
    console.log(fullInfo);
    res.status(201).json(fullInfo);
  } catch (error) {
    console.error(error);
    next(error);
  }
})

이렇게 작성했는데 아무레도 routes에서 문제가 있는 것 같은데 어렵네요.

기존에 등록된 유저의 website 데이터를 일괄 제거한 뒤

문제 1. 배열내에 모든 데이터가 등록되어야하는데 첫번째 데이터만 db에 등록됩니다.

문제 2. add website to me 관련내용은 아예 등록되지도 않습니다.

해결방법이 있을까요? ㅠㅠ

복잡한 질문해서 죄송합니다.

답변 3

0

saga에서 data: result.data.id, --> data: result.data

로 변경해서 해결되었습니다 감사합니다^^

0

감사합니다. 희안하게 callback함수에다 dependancy 값들을 넣어주고난 후에

데이터가 정상적으로 들어오네요

근데 ADD_WEBSITE_TO_ME 에는 여전히 데이터가 들어오지 않네요.

await user.addWebsites(results.map((v) => v[0]));

routes에서 이 값이 잘못된건지 아님 다른 문제인지 모르겠습니다.(ADD_POST_TO_ME와 유사하게 만들었어요)

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

네트워크탭에서 response 확인해보세요. 그리고 result.data도요

0

제로초(조현영)님의 프로필 이미지
제로초(조현영)
지식공유자

서버쪽에서는 req.body 콘솔로그찍어보시고

saga에서는 result.data 찍어보세요.

PaPillOn빠삐용님의 프로필 이미지
PaPillOn빠삐용

작성한 질문수

질문하기