Next.js Discord

Discord Forum

Refetching latest data when navigating to a page after a form submission

Unanswered
Large oak-apple gall posted this in #help-forum
Open in Discord
Large oak-apple gallOP
I have a really basic application where a user can create Flights. The user can fill in a form on the new flights page and after they click submit they should be redirected to the /holiday_plans/id page where they can see their flight information. When I navigate to the page using router.push('/holiday_plans/${holidayPlanId} the data isn't refetched, meaning I need to do a hard refresh to see the newly added flight.

4 Replies

Large oak-apple gallOP
This is the code I'm using in my onSubmit for my form - it's using client-side navigation to send me to the right page:
const onSubmit: SubmitHandler<FlightFields> = async (data) => {
    const response = await createFlight({
      holidayPlanId: holidayPlanId,
      ...data,
    });

    if (response.status === 201) {
      router.push(`/holiday_plans/${holidayPlanId}`);
    }
  };
In my Holiday Plan page I'm getting data by using
const holidayPlan = await getHolidayPlanData(params.uid);
This function is imported from another file, it looks like this:
export const getHolidayPlanData = async (holidayPlanUid: string) => {
  try {
    const response = await fetch(
      `${process.env.APPLICATION_URL}/dev/holiday_planner?holidayPlanUid=${holidayPlanUid}`,
      { cache: "no-store" }
    );

    if (!response.ok) {
      throw new Error(
        `Received a ${response.status} - ${
          response.statusText
        }: ${JSON.stringify(response.body)}`
      );
    }

    const jsonResponse = await response.json();
    console.log(`Got Holiday Plan data for ${holidayPlanUid}:`, jsonResponse);

    return adapt(jsonResponse.data);
  } catch (error) {
    console.error("Failed to fetch holiday plan data:", error);

    throw error;
  }
};
Large oak-apple gallOP
I've found a workaround by updating my code in the onSubmit to use this:
if (response.status === 201) {
      router.push(`/holiday_plans/${holidayPlanId}`);
      router.refresh();
    }
router.refresh(); I see forces a refetch of data. Is there a better way of refetching the data though? I feel this is a bit of a whack solution