mutation.mutate is not a function error
I have a post goal api which is used in various components so im creating a usePostGoal hook which returns mutation. On a click im doing mutation.mutate but it returns
when im using the same mutation without hook it works fine
TypeError: mutation.mutate is not a function
TypeError: mutation.mutate is not a function
2 Replies
rival-blackOP•16mo ago
import { useMutation } from '@tanstack/react-query'
import { APICallWrapper } from '../utils/api-wrapper'
import GoalsService from '../api/services/GoalsService'
export async function useUpdateGoalMutation() {
async function addGoal({ title, body, userId }) {
const res = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title,
body,
userId,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
return res.json()
}
const mutation = useMutation({
mutationFn: addGoal,
onSuccess: (data) => {
console.log('updateGoal response', data)
},
onError: (error) => {
console.error('updateGoal error', error)
},
})
return mutation
}
Here is how im using it
const mutation = useUpdateGoalMutation()
function handleOptionClick(option, index) {
try {
mutation.mutate({
title: 'query',
body: 'Testing',
userId: 1,
})
} catch (error) {
console.error('Error in updating goal', error)
}
}
import { useMutation } from '@tanstack/react-query'
import { APICallWrapper } from '../utils/api-wrapper'
import GoalsService from '../api/services/GoalsService'
export async function useUpdateGoalMutation() {
async function addGoal({ title, body, userId }) {
const res = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title,
body,
userId,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
return res.json()
}
const mutation = useMutation({
mutationFn: addGoal,
onSuccess: (data) => {
console.log('updateGoal response', data)
},
onError: (error) => {
console.error('updateGoal error', error)
},
})
return mutation
}
Here is how im using it
const mutation = useUpdateGoalMutation()
function handleOptionClick(option, index) {
try {
mutation.mutate({
title: 'query',
body: 'Testing',
userId: 1,
})
} catch (error) {
console.error('Error in updating goal', error)
}
}
fair-rose•16mo ago
export async function useUpdateGoalMutation()
export async function useUpdateGoalMutation()