Reputation: 1
I want to use useMutation like useQuery. So I have tried this but this code is not working like my expectation. Here data is coming undefined and isError is false, why? How can I solve this issue?
`import { useMutation } from "@tanstack/react-query";
import axios from "axios";
export const useUserx = () => {
const loginKey = localStorage.getItem("login_key");
const memberId = localStorage.getItem("member_id");
const viewUserProfileData = {
login_key: loginKey,
member_id: memberId
}
const {data, isError, isLoading } = useMutation({
mutationKey: ["user-mutate"],
mutationFn: async () => {
const response = await axios.post('https://example.com/user/profile',
viewUserProfileData )
console.log(response);
return response?.data;
}
})
return {data, isError, isLoading }
}`
Upvotes: 0
Views: 280
Reputation: 540
useMutate
will return you two mutate functions (mutate
and mutateAsync
) which you need to call in order to actually trigger the mutation. So something like this:
import { useMutation } from "@tanstack/react-query";
import axios from "axios";
export const useUserx = () => {
const loginKey = localStorage.getItem("login_key");
const memberId = localStorage.getItem("member_id");
const viewUserProfileData = {
login_key: loginKey,
member_id: memberId
}
return useMutation({
mutationKey: ["user-mutate"],
mutationFn: async () => {
const response = await axios.post('https://example.com/user/profile',
viewUserProfileData )
console.log(response);
return response?.data;
}
})
}
export const UserxComponent = () => {
const { mutate, isError } = useUserx()
return (
<div>
<button onClick={() => mutate()}>Do stuff</button>
{isError && <span>There was an error</span>}
</div>
)
}
Please note that I returned the whole object from useMutation
Upvotes: 0