next.jsfetch

Route Problems with fetch


I currently have a problem in my project that when I try to edit a workout that requires PATCH, it goes to the backend and the database but the edited line is not displayed in the frontend. I have tried it with Postman and there it works great and top but unfortunately this does not work in the frontend code. Although I also have a route.push in the fetch request for the workouts, I can only see the edited file after the manual reload. Has anyone experienced something similar? if so what were your solutions. BTW if it might be relevant for you I don't have the route.push in a useeffect.

try {
    const response = await fetch("/api/update-workout", {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",

      },
      body: JSON.stringify(workoutData),
    });

    if (!response.ok) {
      throw new Error(
        `Fehler beim Aktualisieren des Workouts: ${response.status}`
      );
    }

    await response.json();
    console.log("Workout edit");
    onSuccess();
    router.push("/workout");
  
  } catch (error) {
    console.log("error when updating the workout", error);
  }

I have also tried to deactivate the chash but unfortunately this has not helped me either.


Solution

  • As @Evert pointed out in the comments, the provided code is just a snippet. So, I made certain assumptions.

    It looks like your frontend state isn’t updating after the PATCH. Here’s how you can try to fix it:

    1. Update the State Directly After the API call, update the specific workout in your state instead of waiting for a re-fetch:
        const handleUpdateWorkout = async () => {
      try {
        const response = await fetch request
        });
    
        if (!response.ok) {
          throw new Error(`Error updating workout: ${response.status}`);
        }
    
        const updatedWorkout = await response.json();
    
        // Assuming you have a setState function for workouts
        setWorkouts((prevWorkouts) =>
          prevWorkouts.map((workout) =>
            workout.id === updatedWorkout.id ? updatedWorkout : workout
          )
        );
    
        console.log("Workout edited successfully");
        router.push("/workout");
      } 
    
    
       catch (error) {
            console.error("Error when updating the workout", error);
          }
        };
    
    1. Re-Fetch the Data After a successful PATCH, fetch the latest workouts and update the state before navigating:
    const handleUpdateWorkout = async () => {
      try {
        const response = await fetch("/api/update-workout", {
          method: "PATCH",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify(workoutData),
        });
    
        if (!response.ok) {
          throw new Error(`Error updating workout: ${response.status}`);
        }
    
        console.log("Workout edited successfully");
        await fetchWorkouts(); // Re-fetch the workouts
        router.push("/workout");
      } catch (error) {
        console.error("Error when updating the workout", error);
      }
    };
    

    This ensures the UI reflects the updated data right away. Let me know if it helps!