I am trying to set up a POST and PUT use SWR mutation hook but I keep getting the error: Mutation error: Error: Can’t trigger the mutation: missing key.
Whatever I do, I cannot seem to solve the issue?
Any help would be much appreciated.
Code:
Handle request:
const { triggerMutation, data, error, isMutating } = useCustomSWRMutation();
const handleVenueSubmit = async (data) => {
const venue = {
name: data.name,
address: data.address,
mapLink: data.mapLink,
parkingInfo: data.parkingInfo,
other: data.other,
attachment: "",
clubKey: auth.user.clubId,
key: data.name?.replace(/ /g, ""),
entityStatus: "Active",
};
try {
const method = data.id ? "PUT" : "POST";
const url = data.id
? `${API_URL}/api/venues/${data.id}`
: `${API_URL}/api/venues`;
const headers = {
Authorization: `Bearer ${auth.token}`,
};
// Trigger the mutation with URL, data, method, and headers
const result = await triggerMutation(url, {
arg: venue,
method,
headers,
});
notification.success({
message: data.id
? "Venue updated successfully"
: "Venue added successfully",
description: `${result.name} has been ${data.id ? "updated" : "added"} successfully`,
});
setOpen(false);
} catch (error) {
console.error("Mutation error:", error);
notification.error({
message: data.id ? "Error updating venue" : "Error adding venue",
description: `There was an error ${data.id ? "updating" : "adding"} the venue`,
});
}
};
SWRmutation hook:
import useSWRMutation from "swr/mutation";
const sendRequest = async (url, { arg, method, headers }) => {
const options = {
method: method || "POST", // Default to POST if method is not provided
headers: {
"Content-Type": "application/json",
...headers,
},
body: JSON.stringify(arg),
};
const response = await fetch(url, options);
if (!response.ok) {
const errorData = await response.json();
throw new Error(errorData.message || "Something went wrong");
}
return await response.json();
};
const useCustomSWRMutation = () => {
const { trigger, data, error, isMutating } = useSWRMutation(
null,
sendRequest
);
return { triggerMutation: trigger, data, error, isMutating };
};
export default useCustomSWRMutation;
Getting console error: Mutation error: Error: Can’t trigger the mutation: missing key.