Notice
Recent Posts
Recent Comments
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags more
Archives
Today
Total
관리 메뉴

HYEWON JUNG의 개발일지

20231215 TIL Typescript React-Query TodoList(2) 본문

개발일지

20231215 TIL Typescript React-Query TodoList(2)

혜won 2023. 12. 21. 00:51

목표

  • 과제 완료하기

새로 알게 된것/ 오늘의 코드

react-query 기본 세팅 하기

index.tsx

import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import reportWebVitals from './reportWebVitals';

import { QueryClient, QueryClientProvider } from 'react-query';
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
const queryClient = new QueryClient();
root.render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </React.StrictMode>
);

react- query  넣기 js로

api/todos.ts

import axios from "axios";
const SERVER_URI = "http://localhost:4000";

const getTodos = async () => {
  const response = await axios.get(`${SERVER_URI}/todos`);
  return response.data;
};

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

const removeTodo = async (id) => {//오류
  await axios.delete(`${SERVER_URI}/todos/${id}`);
};

const switchTodo = async (payload) => {//오류
  await axios.patch(`${SERVER_URI}/todos/${payload.id}`, {
    isDone: payload.isDone,
  });
};

export { getTodos, addTodo, removeTodo, switchTodo };

 

props로 받는 얘들이 오류가 발생한다.

 

model 폴더에서 type을 지정하기

model/todos.ts

export type Todos = TodoItem[];
export type TodoItem = {
  id: string;
  content: string;
  title: string;
  isDone: boolean;
};
export type SwitchPayload = {
  id: string;
  isDone: boolean;
};

 api 수정해주기

import axios from "axios";
import { TodoItem } from "../model/todos";  //model 폴더의type 가져오기
import { SwitchPayload } from "../model/todos"; //model 폴더의type 가져오기
const SERVER_URI = "http://localhost:4000";

const getTodos = async () => {
  const response = await axios.get(`${SERVER_URI}/todos`);
  return response.data;
};

const addTodo = async (newTodo: TodoItem) => { //타입 넣어주기
  await axios.post(`${SERVER_URI}/todos`, newTodo);
};

const removeTodo = async (id: string) => { //타입 넣어주기
  await axios.delete(`${SERVER_URI}/todos/${id}`);
};

const switchTodo = async (payload: SwitchPayload) => { //타입 넣어주기
  await axios.patch(`${SERVER_URI}/todos/${payload.id}`, {
    isDone: payload.isDone,
  });
};

export { getTodos, addTodo, removeTodo, switchTodo };

 

api를 이용해서 usequery, useMutation 하기

1. getTodos (useQuery() 사용 )

components/Todolist.tsx

  const { isLoading, isError, data } = useQuery('todos', getTodos, {
    staleTime: 1000,
    retry: 7 //연결 시도 횟수
  });

  if (isLoading) {
    return <p>로딩중입니다....!</p>;
  }

  if (isError) {
    return <p>오류가 발생하였습니다...!</p>;
  }

 

2. addTodo(useMutation()사용)

components/Form.tsx


  const queryClient = useQueryClient();
  const mutation = useMutation(addTodo, {
    onSuccess: (data) => {
      //입력이 되면
      console.log('data', data);
      queryClient.invalidateQueries('todos'); //성공하면 todos를 invalidate 해
    }
  });
  
    const handleSubmitButtonClick = async (event) => {
    // submit의 고유 기능인, 새로고침(refresh)을 막아주는 역함
    event.preventDefault();

    // 추가하려는 todo를 newTodo라는 객체로 세로 만듦
    const newTodo = {
      id: uuid(),
      title,
      content,
      isDone: false
    };

    // 인자 : payload
    if (!title || !content) {
      alert('빈칸없이 작성해 주세요!');
    } else {
      mutation.mutate(newTodo);
      setTitle('');
      setContent('');
    }
  };

3. removeTodo (useMutation())

components / Todo.tsx

  const queryClient = useQueryClient();

  const deleteMutation = useMutation(removeTodo, {
    onSuccess: () => {
      queryClient.invalidateQueries('todos');
    }
  });
  
    const handleRemoveButton = () => {
    deleteMutation.mutate(todo.id);
  };

4. switchTodo(useMutation())

components/Todo.tsx

  const switchMutation = useMutation(switchTodo, {
    onSuccess: () => {
      queryClient.invalidateQueries('todos');
    }
  });
  
    const handleSwitchButton = () => {
    const payload = {
      id: todo.id,
      isDone: !todo.isDone
    };
    console.log(todo.id, !todo.isDone);
    switchMutation.mutate(payload);
  };

 

실행하면 당근 빳따 오류가 난다. type지정을 해주지 않았기 때문이다. 

???: 어디에 타입이 필요한디?

  const handleSubmitButtonClick = async (event: (event에 타입이 필요해요)) => {
    // submit의 고유 기능인, 새로고침(refresh)을 막아주는 역함
    event.preventDefault();

    // 추가하려는 todo를 newTodo라는 객체로 세로 만듦
    const newTodo = {
      id: uuid(),
      title,
      content,
      isDone: false
    };

    // 인자 : payload
    if (!title || !content) {
      alert('빈칸없이 작성해 주세요!');
    } else {
      mutation.mutate(newTodo);
      setTitle('');
      setContent('');
    }
  };

 

addTodo에 event에 타입이 필요하다!

Form 태그에 submit을 준 것 이니

(event: React.FormEvent<HTMLFormElement>)

이렇게 넣어주면된다.

 

개념정리

redux 에서 query로 변경할 때 

데이터 가져오기

 useSelector -> useQuery

CUD하기

useDispatch -> useMutation

목표 달성여부

  • 과제 완료하기 TIL 정리는 나눠서하기

내일 목표

  • TIL 정리하기