Updates or Delete data with same id twice upon response delay from backend. #6957
Unanswered
hamzaalikhan1122
asked this question in
Q&A
Replies: 1 comment
-
TypeError: Failed to fetch
|
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I am currently learning Udemy React course, in instructor video, he didn't get the error but when I try to update or delete any event. it givees 404 error. when I console.log request in backend, useMutation, sends same request twice before even getting response & as a result, it neither navigated not updated the component & also throw 404 error. when I navigate or reload, data already updated or deleted. Kindly tell me how can I fix this issue?
Frontend Code
import {
Link,
useNavigate,
useParams,
useSearchParams,
} from "react-router-dom";
import Modal from "../UI/Modal.jsx";
import EventForm from "./EventForm.jsx";
import { QueryCache, useMutation, useQuery } from "@tanstack/react-query";
import {
deleteEvent,
fetchEvent,
queryClient,
updateEvent,
} from "../../util/http.js";
import ErrorBlock from "../UI/ErrorBlock.jsx";
export default function EditEvent() {
const navigate = useNavigate();
const params = useParams();
const { data, isError, isPending, error } = useQuery({
queryKey: ["events", params.id],
});
const {
mutate,
isError: isErrorUpdating,
isPending: isPendingUpdation,
error: updateError,
} = useMutation({
mutationFn: updateEvent,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["events"] });
navigate("/events");
},
});
function handleSubmit(formDataEdit) {
mutate({ formData: { id: params.id, event: formDataEdit } });
}
function handleClose() {
navigate("../");
}
return (
{isError && (
<ErrorBlock
title="Error while editing event"
message={
error.info?.message ||
"An error occurred while fetching event data for editing."
}
/>
)}
{isPending &&
Fetching Data...
}{data && (
{isPendingUpdation &&
Data is updating...
}{!isPendingUpdation && (
<>
{" "}
Cancel
Update
</>
)}
)}
{isErrorUpdating && (
<ErrorBlock
title="Error while updating data"
message={
updateError.info?.message ||
"There was an error updating event. Please try again later."
}
/>
)}
);
}
API Query Function:
export async function updateEvent({ formData }) {
console.log(formData);
const response = await fetch(
http://localhost:3000/events/${formData.id}
, {method: "PUT",
body: JSON.stringify(formData),
headers: {
"Content-Type": "application/json",
},
});
if (!response.ok) {
const error = new Error(
"An error occurred while updating Event with id:" + formData.id
);
error.code = response.status;
error.info = await response.json();
throw error;
}
const { event } = await response.json();
return event;
}
Backend code:
app.put("/events/:id", async (req, res) => {
const { id } = req.params;
const { event } = req.body;
console.log(event);
if (!event) {
return res.status(400).json({ message: "Event is required" });
}
if (
!event.title?.trim() ||
!event.description?.trim() ||
!event.date?.trim() ||
!event.time?.trim() ||
!event.image?.trim() ||
!event.location?.trim()
) {
return res.status(400).json({ message: "Invalid data provided." });
}
const eventsFileContent = await fs.readFile("./data/events.json");
const events = JSON.parse(eventsFileContent);
const eventIndex = events.findIndex((event) => event.id === id);
if (eventIndex === -1) {
return res.status(404).json({ message: "Event not found" });
}
events[eventIndex] = {
id,
...event,
};
await fs.writeFile("./data/events.json", JSON.stringify(events));
setTimeout(() => {
res.json({ event: events[eventIndex] });
}, 1000);
});
Beta Was this translation helpful? Give feedback.
All reactions