«   2024/09   »
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
Archives
Today
Total
Recent Posts
Recent Comments
관리 메뉴

뉴히의 개발 로그

[TIL] 20230710 - React Query(get/post/patch/delete) 본문

개발일지/TIL

[TIL] 20230710 - React Query(get/post/patch/delete)

뉴히 2023. 7. 11. 01:04

리덕스를 사용하지 않고 json-server에 데이터 저장후

리액트 쿼리로 app.jsx에 

<QueryClientProvider client={queryClient}>

로 감싸주면 전체 파일에서 query에 접근해서 사용할 수 있다.

// App.jsx

const queryClient = new QueryClient();

const App = () => {
    return (
        <QueryClientProvider client={queryClient}>
            <Router />
        </QueryClientProvider>
    );
};

 

api폴더에 전체 모듈을 모아 작성해주고

// axios 요청이 들어가는 모든 모듈
import axios from 'axios';

//조회
const getTodos = async () => {
    const response = await axios.get(`${process.env.REACT_APP_SERVER_URL}/todos`);
    return response.data;
};

// 추가
const addTodo = async (newTodo) => {
    await axios.post(`${process.env.REACT_APP_SERVER_URL}/todos`, newTodo);
};

// 삭제
const removeTodo = async (id) => {
    await axios.delete(`${process.env.REACT_APP_SERVER_URL}/todos/${id}`);
};

// 수정
const switchTodo = async (id) => {
    const idAllDate = await axios.get(`${process.env.REACT_APP_SERVER_URL}/todos/${id}`);
    const todo = idAllDate.data;
    const updateTodo = {
        ...todo,
        isDone: !todo.isDone
    };
    console.log(updateTodo);
    await axios.patch(`${process.env.REACT_APP_SERVER_URL}/todos/${id}`, updateTodo);
};

export { getTodos, addTodo, removeTodo, switchTodo };

등록 컴포넌트(Input.jsx)에 mutation.mutate만 해주면 등록 가능!

//Input.jsx

// 리액트 쿼리 관련 코드
const queryClient = useQueryClient();
const mutation = useMutation(addTodo, {
    onSuccess: () => {
        queryClient.invalidateQueries('todos');
    }
});
    
    
const handleSubmitButtonClick = (event) => {
        event.preventDefault();
        
        const newTodo = {
            title,
            contents,
            isDone: false,
            id: uuidv4()
        };

        mutation.mutate(newTodo);
};

수정또한 id를 받아와서 내용을 업데이트 해주면 되는데

id에 데이터를 한번 불러와서 isDone을 바꿔줬기 때문에 id, isDone 두개의 인자를 받지않고 id만 받아서 수정업데이트가 가능하다.

 

삭제시에는 mutation없이도 삭제가 가능하다. 

+ 수정 : 삭제는 가능하지만 실시간으로 적용해주기 위해서 invalidateQueries를 해줘야 한다! mutation 써야함!!

 // 리액트 쿼리 관련 코드
    const queryClient = useQueryClient();
    const mutation = useMutation(switchTodo, {
        onSuccess: () => {
            queryClient.invalidateQueries('todos');
        }
    });
    const mutation2 = useMutation(removeTodo, {
        onSuccess: () => {
            queryClient.invalidateQueries('todos');
        }
    });
    
// 완료, 취소를 handling하는 함수
    const handleSwitchButton = () => {
        mutation.mutate(todo.id);
    };
    
    
// [삭제] 버튼 선택 시 호출되는 함수(user의 confirmation 필요)
    const handleRemoveButton = () => {
        if (window.confirm(CONFIRM_MESSAGE)) mutation2.mutate(todo.id);
    };