단어 추가, 수정, 삭제

김_리트리버·2020년 7월 11일
0

단어추가

👉 구현방법

  • 입력되는 단어를 state 로 설정, 입력할 때마다 변화를 적용
  • 버튼을 눌렀을 때 state 로 설정한 단어를 서버에 보낸다.

    cf
    받아온 단어목록 중 입력한 단어가 있으면 서버로 요청이 가지 않도록 방지한다.


 postInputWord() {
    // post 요청: 유저가 입력한 새로운 단어/예문을 서버에 전송한다.
    // const url = 'http://localhost:8080/words';
    const url = 'http://localhost:8080/words';
    axios
      .post(url, {
        word: this.state.currentWord,
      })
      .then((res) => {
        // test 위해 넣은 code
        // 실제론 아래 TODO 로 변경해야 함
        this.setState({ wordData: res.data.data });
      })
      .then(() => {
        this.getWordData();
      });
  }

////////////////////////////////////////////////////////////////
  submitWord(e) {
    e.preventDefault();

    const findingWord = this.props.currentWord;

    let findResult = this.props.word.find(function (word) {
      return word === findingWord;
    })

    if (findResult) {
      alert('이미 단어장에 있는 단어입니다!');
      document.querySelector('.word_input').value = '';
    } else {
      // TODO: 무조건 서버에 보내고 get 으로 받아서 data 를 초기화 시켜야 함
      this.props.postInputWord();
    }

    document.querySelector('.word_input').value = '';
  }

👉 아쉬운점

  • 검색기능은 단어입력 버튼을 눌렀을 때 실행되는데 입력되는 단어를 state 로 관리할 이유가 없었다.
  • 버튼을 눌렀을 때의 값으로 단어가 단어장에 있는 지 검색한 후 없으면 단어를 서버로 보내는 방식이 state 변경을 최소화 할 수 있어 render() 호출을 적게 할 수 있다.

👉 Refactoring


 postInputWord(word) {
    const url = 'http://localhost:8080/words';
    axios
      .post(url, {
        word: word,
      })
      .then((res) => {
        // test 위해 넣은 code
        // 실제론 아래 TODO 로 변경해야 함
        this.setState({ wordData: res.data.data });
      })
      .then(() => {
        this.getWordData();
      });
  }

////////////////////////////////////////////////////////////////////////
 
submitWord(e) {
    e.preventDefault();

   const inputWord = document.querySelector('.word_input').value

    let findResult = this.props.word.find(function (word) {
      return word === inputWord;
    })

    if (findResult) {
      alert('이미 단어장에 있는 단어입니다!');
      document.querySelector('.word_input').value = '';
    } else {
      // TODO: 무조건 서버에 보내고 get 으로 받아서 data 를 초기화 시켜야 함
      this.props.postInputWord(inputWord);
      document.querySelector('.word_input').value = '';
    }

  }

문장추가

👉 구현방법

  • 입력되는 문장1,2,3 을 state 로 설정하여 변경될 때 마다 state 에 반영
  • 확인버튼을 누르면 단어, 단어key(DB에서 받은), state 로 설정된 문장들을 서버로 보냄

function createSentences() {

     let wordObj = {
      wordId: index,
      word: modalWord,
      sentences: [sentenceFirst, sentenceSecond, sentenceThird],
    };

    addSentences(wordObj);
  }

  addSentences(wordObj) {
 
    const url = 'http://localhost:8080/words';
    let word = {};
    word[wordObj.wordId] = wordObj.word;
    let sentences = wordObj.sentences;
    let addSentenceObj = { word: word, sentences: sentences };
    // {word:{1:'adsfasdfa'},sentence:['a','b','c']}
    axios
      .post(url, addSentenceObj)
      .then((res) => {
        console.log('addSentences',res)
        this.setState({ wordData: res.data.data });
      })
      .then(() => {
        this.getWordData();
      });
  }

 

👉 아쉬운점

  • 서버에 보낼 문장, 단어를 state 로 관리해야할 필요가 없었음
  • 버튼을 눌렀을 때만 input 에서 data 를 받아서 보낸다면 state 변화를 줄일 수 있었음

👉 Refactoring

 function createSentences() {

    const sentenceOne = document.querySelector('.sentenceOne').value;
    const sentenceTwo = document.querySelector('.sentenceTwo').value;
    const sentenceThree = document.querySelector('.sentenceThree').value;
    const word  = document.querySelector('.modal_word').value;

    let wordObj = {
      wordId: index,
      word: word,
      sentences: [sentenceOne, sentenceTwo, sentenceThree],
    };

    addSentences(wordObj);
  }

단어수정

👉 구현방법

  • 단어, 문장을 state 로 설정한 후 버튼을 눌렀을 때 단어와 문장들을 기존 서버에서 받은 단어ID, 문장ID 와 함께 보내 수정하도록 하였음
// 서버에 문장을 보내는 형식 sentence: {1:'ㅁㄴ온ㅇ로',10:'ㅅ논ㅇㄹ',89:'ㅂㅂ'} 
  function mapSentence() {

    let modalSentence = [sentenceFirst, sentenceSecond, sentenceThird];
    let updateSentenceObj = {};

    let sentenceKey = Object.keys(sentences);
	// DB 에서 받은 ID 에 데이터를 덮어씌우기 위함 
    for (let i = 0; i < sentenceKey.length; i++) {
      updateSentenceObj[sentenceKey[i]] = modalSentence[i];
    }

    let WordObject = {
      wordId: index,
      word: modalWord,
      sentences: updateSentenceObj,
    };

    return WordObject;
  }

updateWordData(wordObj) {
  
  
    const url = 'http://localhost:8080/words';
    let sendWord = {};
    sendWord[wordObj.wordId] = wordObj.word;
    let sendObj = {};
    sendObj['word'] = sendWord;
    sendObj['sentences'] = wordObj.sentences;
    axios
      .post(url, sendObj)
      .then((res) => {
        this.setState({ wordData: res.data.data });
      })
      .then(() => {
        this.getWordData();
      });
  }

👉 아쉬운점

  • 서버에 보낼 문장, 단어를 state 로 관리해야할 필요가 없었음
  • 버튼을 눌렀을 때만 input 에서 data 를 받아서 보낸다면 state 변화를 줄일 수 있었음
  • 초기에 작성한 코드는 기존에 서버로부터 받은 문장ID 에 현재 입력한 문장이 덮어씌워지도록 구성하였는데 큰 문제가 있었다.
  • test 과정에서 문장을 1개 저장한 다음 다시 수정하려 할때 문장을 추가할 수 없는 것을 발견하였다.
  • 서버로 부터 받은 문장ID 갯수만큼 수정할 수 밖에 없도록 코드를 구성한 것을 발견함
  • 테스트 이후 서버로 부터 받은 문장 ID 수보다 문장을 추가로 수정할 경우 새롭게 문장을 추가시키는 것으로 해결하였다.
  • 코드를 구성하기전 error 가능성에 대해 생각하지 않고 코드를 작성하여 테스트 과정에서 오류가 발생하였다.

👉 Refactoring


  function mapSentence() {

    const sentenceOne = document.querySelector('.sentenceOne').value;
    const sentenceTwo = document.querySelector('.sentenceTwo').value;
    const sentenceThree = document.querySelector('.sentenceThree').value;
    const word  = document.querySelector('.modal_word').value;
    let modalSentence = [sentenceOne,sentenceTwo,sentenceThree];
    let updateSentenceObj = {};

    let sentenceKey = Object.keys(sentences);

    for (let i = 0; i < sentenceKey.length; i++) {
      updateSentenceObj[sentenceKey[i]] = modalSentence[i];
    }

    let WordObject = {
      wordId: index,
      word: word,
      sentences: updateSentenceObj,
    };

    return WordObject;
  }

단어삭제

👉 구현방법

  • 단어를 삭제할 때는 단어와 연관된 문장도 같이 삭제되도록 함

  deleteWordData(wordObj) {
  
    const url = 'http://localhost:8080/words';
    const { wordId } = wordObj;
    const wordIdobj = { wordId: wordId };

    axios
      .delete(url, {
        data: wordIdobj,
        withCredentials: true,
      })
      .then((res) => {
        this.setState({ wordData: res.data.data });
      })
      .then(() => {
        this.getWordData();
      });
   
  }

👉 아쉬운점

  • 개별 문장을 삭제하는 기능을 구현하지 못한 점
  • 단어 ID 만 필요한데 쓸모없는 data 를 arguments 로 보낸점

👉 Refactoring


 deleteWordData(wordId) {
    // TODO: sentenceIds => sentence Id 배열
    // delete 요청: 유저가 단어/예문을 삭제한 경우 서버에 삭제를 요청한다.
    // const url = 'http://localhost:8080/words';
    const url = 'http://localhost:8080/words';
    // api 형식에 맞추기 위함
    const wordIdobj = {};
    wordIdobj.wordId=wordId;

    axios
      .delete(url, {
        data: wordIdobj,
        withCredentials: true,
      })
      .then((res) => {
        this.setState({ wordData: res.data.data });
      })
      .then(() => {
        this.getWordData();
      });
    // wordId 가 배열 index 보다 1 크기 때문에 조정함
  }

📖 총평

  1. 초기 설계 실패로 인한 시간낭비

    초기에 단어 데이터 추가,수정,삭제를 구현할 때 유저가 여러명 있을 때를 고려하지 않아 처음에 서버로 부터 데이터를 받아온 이후 get 요청을 보내지 않아도 될 것으로 생각했다.
    post 요청시 client 에서도 단어를 추가, 수정, 삭제 한다면 post 요청 이후 서버로 부터 데이터를 받아오지 않아도 될 것으로 생각했지만 유저가 여러명 있다는 것을 고려하니 이는 완전히 잘못된 생각이었다.
    이후 단어를 추가, 수정, 삭제 요청시 바로 서버로 부터 데이터를 받아와 데이터베이스와 동기화 시키는 방식으로 변경하였다.
    하지만 검색의 경우 find 메서드를 사용하여 client 에서 검색할 수 있도록 하여 서버 자원을 사용하는 것을 줄일 수 있었다.

  2. 문장 추가,수정 기능에서 초기 설계 실패로 인한 error 발생

    초기에 작성한 코드는 기존에 서버로부터 받은 문장ID 에 현재 입력한 문장이 덮어씌워지도록 구성하였는데 큰 문제가 있었다.
    이후 test 과정에서 문장을 1개 저장한 다음 2번, 3번 문장을 추가하려 할때 문장을 추가할 수 없는 것을 발견하였다.
    원인은 서버로 부터 받은 문장ID 갯수만큼 수정할 수 밖에 없도록 코드를 구성한 것이었음을 발견하였다. 이후 서버로 부터 받은 문장 ID 수보다 문장을 추가로 수정할 경우 새롭게 문장을 추가시키는 것으로 해결하였다.
    빨리 작성하기 위해 코드를 구성하기전 error 가능성에 대해 생각하지 않고 코드를 작성하여 더 많은 시간이 소모되었다.

profile
web-developer

0개의 댓글