Skip to content

Files

Latest commit

Mar 5, 2024
9bce433 ยท Mar 5, 2024

History

History
64 lines (49 loc) ยท 1.41 KB

useMutation.md

File metadata and controls

64 lines (49 loc) ยท 1.41 KB

useMutation

React-Query๋กœ ์„œ๋ฒ„์— ๋ณ€๊ฒฝ ์ž‘์—… ์š”์ฒญ ์‹œ ์‚ฌ์šฉ (insert, update, delete)

mutationFn

axios๋ฅผ ์ด์šฉํ•ด ์„œ๋ฒ„์— api ์š”์ฒญ

const deleteData = useMutation(() => axios.delete(`api/delete/${id}`));

const deleteData = useMuatation({
	mutationFn: (id) => axios.delete(`api/delete/${id}`)
})

mutate

useMutation ์ด์šฉ โ†’ ์ž‘์„ฑํ•œ ๋‚ด์šฉ์ด ์‹ค์ œ๋กœ ์‹คํ–‰๋  ์ˆ˜ ์žˆ๋„๋ก ๋„์›€ ์ด๋ฒคํŠธ ๋ฐœ์ƒ ์‹œ ์‚ฌ์šฉ

const {mutate} = () => deleteData()

const deleteFm = () => {
	deleteData.mutate(id)
}

onSuccess, onError, onSettled

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 ๊ทธ๋Œ€
})

onMutate

์„ฑ๊ณต ์‹œ ํ˜„์žฌ ๋ฐ์ดํ„ฐ ์บ์‹œ ์—…๋ฐ์ดํŠธ or UI ๋ณ€๊ฒฝ onMutate callback ํ•จ์ˆ˜์—์„œ UI ์—…๋ฐ์ดํŠธ ํ›„ setQueryData ํ•จ์ˆ˜๋กœ ์ด์ „ ๋ฐ์ดํ„ฐ ์—…๋ฐ์ดํŠธ