React-Query๋ก ์๋ฒ์ ๋ณ๊ฒฝ ์์ ์์ฒญ ์ ์ฌ์ฉ (insert, update, delete)
axios๋ฅผ ์ด์ฉํด ์๋ฒ์ api ์์ฒญ
const deleteData = useMutation(() => axios.delete(`api/delete/${id}`));
const deleteData = useMuatation({
mutationFn: (id) => axios.delete(`api/delete/${id}`)
})
useMutation ์ด์ฉ โ ์์ฑํ ๋ด์ฉ์ด ์ค์ ๋ก ์คํ๋ ์ ์๋๋ก ๋์ ์ด๋ฒคํธ ๋ฐ์ ์ ์ฌ์ฉ
const {mutate} = () => deleteData()
const deleteFm = () => {
deleteData.mutate(id)
}
const deleteData = async () => {
try {
const res = await axios.delete(`api/delete/${id}`)
.then((res) => console.log(res.data))
} catch(err) {
console.error('error', err.message)
} finally {
console.log('์คํ')
}
}
// key ๊ฐ ์๋ต
const deleteData = useMutation((id) => axios.delete(`api/delete/${id}`), {
onSuccess: () => {console.log('์์ฒญ ์ฑ๊ณต')},
onError: () => {console.log('์๋ฌ ๋ฐ์')},
onSettled: () => {console.log('๊ฒฐ๊ณผ์ ์๊ด x -> ๋ฌด์ธ๊ฐ ์คํ')}
})
// key ๊ฐ ๋ช
์
const deleteData = useMutation({
mutationFn: (id) => axios.delete(`api/delete/${id}`),
// onSuccess, onError, onSettled ๊ทธ๋
})
์ฑ๊ณต ์ ํ์ฌ ๋ฐ์ดํฐ ์บ์ ์ ๋ฐ์ดํธ or UI ๋ณ๊ฒฝ onMutate callback ํจ์์์ UI ์ ๋ฐ์ดํธ ํ setQueryData ํจ์๋ก ์ด์ ๋ฐ์ดํฐ ์ ๋ฐ์ดํธ