mutationFn
// ์ฒซ ๋ฒ์งธ ๋ฐฉ๋ฒ
const deleteData = useMutation(() => axios.delete(`api/delete/${id}`));
// ๋ ๋ฒ์งธ ๋ฐฉ๋ฒ
const deleteData = useMutation({
mutationFn: (id) => axios.delete(`api/delete/${id}`)
})
mutate
const { mutate } = () => deleteData()
const deleteFn = () => {
deleteData.mutate(id)
}
onSuccess, onError, onSettled
async/await ๋ง ์ฌ์ฉํ์ ๋
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('์ด์จ๋ ์คํ๋๋ ๋ถ๋ถ')
}
}
useMutation ์ ์ฉ ์
// fn key ๊ฐ ์๋ต๋ ๋ฒ์
const deleteData = useMutation((id) => axios.delete(`api/delete/${id}`), {
onSuccess: () => { console.log('์์ฒญ ์ฑ๊ณต') },
onError: () => { console.error('์๋ฌ ๋ฐ์') },
onSettled: () => { console.log('๊ฒฐ๊ณผ์ ๊ด๊ณ ์์ด ๋ฌด์ธ๊ฐ ์คํ๋จ') }
})
// fn key ๊ฐ ๋ช
์๋ ๋ฒ์
const deleteData = useMutation({
mutationFn: (id) => axios.delete(`api/delete/${id}`),
onSuccess: () => { console.log('์์ฒญ ์ฑ๊ณต') },
onError: () => { console.error('์๋ฌ ๋ฐ์') },
onSettled: () => { console.log('๊ฒฐ๊ณผ์ ๊ด๊ณ ์์ด ๋ฌด์ธ๊ฐ ์คํ๋จ') }
})
onMutate
const queryClient = useQueryClient(() => axios.post(`api/like/${id}`), {
onMutate: async (id) => {
// 'queryKey'๋ก ์งํ ์ค์ธ refetch ์ทจ์ํ์ฌ ๋๊ด์ ์
๋ฐ์ดํธ๋ฅผ ๋ฎ์ด์ฐ์ง ์๋๋ก ํจ
await queryClient.cancleQueries({
queryKey: ['queryKey]
})
// ์ด์ ๋ฐ์ดํฐ๋ฅผ ๋ฐ์์ด
const previousData = queryClient.getQueryData(['queryKey']);
// ์๋ก์ด ๊ฐ์ผ๋ก ๋๊ด์ ์
๋ฐ์ดํธ
queryClient.setQueryData(['queryKey'], (prev) => !prev)
return { previousData }
},
// mutation์ด ์คํจํ ๊ฒฝ์ฐ
onError: (err, newData, context) => {
// onMutate๋ก๋ถํฐ ๋ฐํ๋ context๋ฅผ ์ฌ์ฉํ์ฌ rollback
queryClient.setQueryData(['queryKey'], context.previousData)
},
onSettled: () => {
// ์ฑ๊ณต, ์คํจ ์ฌ๋ถ์ ๊ด๊ณ ์์ด refetch
queryClient.invalidateQueries({queryKey: ['queryKey']})
}
});
const deleteData = useMutation({
})
invalidateQueries
const queryClient = useQueryClient(); // ๋ฑ๋ก๋ queryClient๋ฅผ ๊ฐ์ ธ์ด
const deleteData = useMutation((id) => axios.delete(`api/delete/${id}`), {
onSuccess: () => {
console.log('์์ฒญ ์ฑ๊ณต');
// ์์ฒญ ์ฑ๊ณต ์ ํด๋น queryKey ์ ํจ์ฑ ์ ๊ฑฐ
queryClient.invalidateQueries('queryKey')
},
onError: () => { console.error('์๋ฌ ๋ฐ์') },
onSettled: () => { console.log('๊ฒฐ๊ณผ์ ๊ด๊ณ ์์ด ๋ฌด์ธ๊ฐ ์คํ๋จ') }
})