[to do list] API 연동 - 데이터 체크박스 처리하기

youngseo·2022년 2월 25일
0

JS프로젝트

목록 보기
4/18
post-thumbnail

API 연동 - 데이터 체크박스 처리하기

체크박스에 체크가 되면, db.json파일의 completedtrue가 체크박스가 해제가 되는 경우 false가 되는 동작을 구현해보도록 하겠습니다.

이 동작의 경우 fetch로 통신을 할 때 부분적으로 수정이 되도록 진행을 하게 될 것입니다.

1. 체크박스 체크 시 이벤트발생

1-1 기본틀

  const toggleTodo = () => {}

  const init = () => {
    window.addEventListener('DOMContentLoaded', () => {
      getTodos()
    })
    $form.addEventListener('submit', addTodo)
    $todos.addEventListener('click', toggleTodo)
  }

1-2 해당 클래스이름에 맞는 요소 찾기

현재 $todos에 이벤트를 걸었기 때문에, 해당 요소의 어떤 부분에 클릭을 해도 이벤트가 작동하게 됩니다. 따라서 className을 이용해 todo_checkbox 클래스를 체크한 경우에만 동작을 하게금 만들어줍니다.

  const toggleTodo = (e) => {  
    //className이 todo_checkbox가 아닌 경우 리턴
    if (e.target.className !== 'todo_checkbox') return
  }

1-3 몇 번째 item에 해당하는지 찾기

  const toggleTodo = (e) => {  
    if (e.target.className !== 'todo_checkbox') return
    const $item = e.target.closest('.item')       ---(1)
    const id = $item.dataset.id                   ---(2)
  }

(1) 몇 번째 체크 박스인지 구분을 하기 위해 가장 가까운 className이 item인 요소를 찾아옵니다.
     ex) <div calss = "item" data-id="1">
(2) 찾은 값에서 data-id를 찾아옵니다.
     ex) 1

1-4 체크박스 상태가져오기

  const toggleTodo = (e) => {  
    const $item = e.target.closest('.item') 
    const id = $item.dataset.id 
    const completed = e.target.checked               ---✔️
  }

1-5 특정 아이디와 통신하기

  const toggleTodo = (e) => {  
    if (e.target.className !== 'todo_checkbox') return
    const $item = e.target.closest('.item') 
    const id = $item.dataset.id 
    const completed = e.target.checked

    fetch(`${API_URL}/${id}`, {                       ---(1)
      method: 'PATCH',                                ---(2)
      headers: { 'Content-type': 'application/json' }, 
      body: JSON.stringify({ completed }),             --(3)
    })
  }

(1) 특정 id와의 통신을 위해 ${API_URL}/${id}으로 URL뒤에 /아이디값을 명시해줍니다.
(2) put은 전체를 교체할 때 patch는 부분을 교체할때 사용할 수 있습니다.
(3) 변경할 특정요소만 적어줍니다.

정상적으로 동작을 하는 것을 확인할 수 있습니다.

1-6 리스트 새로고침 및 에러처리

    fetch(`${API_URL}/${id}`, {
        method: 'PATCH',
        headers: {
          'Content-type': 'application/json'
        },
        body: JSON.stringify({
          completed
        }),
      }).then((response) => response.json())
      .then(getTodos)
      .catch((error) => console.error(error))
  }

1-7 completed처리

createTodoElement 안의 type="checkbox" 요소 안에서 체크박스처리를 해 프로젝트가 브라우저에 처음 오픈되었을 때 체크여부가 데이터의 completed따라 달라질 수 있도록 처리를 해줍니다.

  const createTodoElement = (item) => {
    const {id, content,completed} = item   -------(1)completed추가
    const isChecked = completed ? 'checked' : ''---(2)추가
      ...
    $todoItem.innerHTML = `
            <div class="content">
              <input
                type="checkbox"
                class='todo_checkbox' 
                ${isChecked}                -------(3) 추가
              />

0개의 댓글