기존에 했던 간단한 Todo List 프로젝트를 React Query를 이용한 데이터 관리로 바꾸어 주었다.

추가)

- 반복되는 useState -> customHook

- MUI alert창

- JS Doc 주석 경험.

 

Todos CRUD 따로 빼주기

// api/todos

import axios from "axios";
import { useQuery } from "react-query";

// 모든 todos를 가져오는 api
const SERVER_URI = process.env.REACT_APP_SERVER_URI;

/**
 * todo 리스트를 가져옵니다.
 */
const getTodos = async () => {
  const response = await axios.get(`${SERVER_URI}/todos`);
  return response.data;
};

/**
 * 새로운 todo를 추가시켜줍니다.
 */


const addTodo = async (newTodo) => {
  await axios.post(`${SERVER_URI}/todos`, newTodo);
};

/**
 * todo를 삭제시켜줍니다.
 */
const deleteTodo = async (id) => {
  await axios.delete(`${SERVER_URI}/todos/${id}`);
};

/**
 *  todo를 수정시켜줍니다.
 */
const editTodo = async (updatedTodo) => {
  await axios.patch(`${SERVER_URI}/todos/${updatedTodo.id}`, updatedTodo);
};

export { getTodos, addTodo, deleteTodo, editTodo };

 

- 다른 컴포넌트에서 함수로 사용하게끔 할 수 있게 따로 분류해두었다.

- SERVER_URI는 민감한 정보가 될수 있으므로 .env 파일에 따로 분류해두었다.


할 일 추가

 

  //Form.jsx
  
    // 할 일 추가
  const queryClient = useQueryClient();
  const addMutation = useMutation(addTodo, {
    onSuccess: () => {
      queryClient.invalidateQueries("todos");
    },
  });

  
  const handleAddButtonClick = (e) => {
    e.preventDefault();

    if (validation()) {
      const id = shortid.generate();
      const newTodo = {
        writer,
        title,
        contents,
        password,
        id,
        timer,
        isDone: false,
      };
      addMutation.mutate(newTodo);

      alert("성공");
      navigate("/list");
    } else {
      alert("실패");
    }
  };

- Mutaion은 CUD에서 쓰인다.

- 중간에 Query Client 메서드로 "invalidateQueries(무효화)"를 사용한다.  캐시를 무효화하는 이유는 사용자가 페이지를 새로고침 할 필요가 없게 데이터를 업데이트 시킨다.

 


 

Custom Hook 사용

// src/hooks/useInput.js

import React, { useState } from "react";

const useInput = () => {
	// value는 useState로 관리하고, 
  const [value, setValue] = useState("");

	// 핸들러 로직도 구현합니다.
  const handler = (e) => {
    setValue(e.target.value);
  };

  // 값 초기화 해줍니다.
  const reset= ()=>{
    setValue("");
  }



	// 이 훅은 [ ] 을 반환하는데, 첫번째는 value, 두번째는 핸들러를 반환합니다.
  return [value, handler, reset];
};

export default useInput;
// Form.jsx

// 커스텀 훅 사용
  const [writer, onChangeWriterHandler, writerReset] = useInput("");
  const [title, onChangeTitleHandler, titleReset] = useInput("");
  const [contents, onChangeContentsHandler, contentsReset] = useInput("");
  const [password, onChangePasswordHandler, passwordReset] = useInput("");
  
  const validation = function () {
    if (writer.length < 2) {
      alert("이름을 2글자 이상 작성해주세요!");
      init();
      return false;
          ...
     } 
 
  
    function init() {
    writerReset();
    titleReset();
    contentsReset();
    passwordReset();
    
  }

 

   <TextField
                id="outlined-basic"
                label="작성자"
                variant="outlined"
                value={writer}
                inputProps={{
                  maxLength: 10,
                }}
                placeholder="이름 입력 (2자 이상)"
                onChange={onChangeWriterHandler}
              ></TextField>
              ...

 

- 반복되는 useState는 따로 분류해두었다.

 


결과물

 


 

마무리

-React Query가 생소해서 적용시키기 힘들었지만 

적응되면 많이 쓰일 거 같다.

 

 

 

+ Recent posts