Manjot Singh
Manjot Singh

Reputation: 9

How can I revalidate the cache of a route handler on demad?

I am fetching some data from an API without manually specifying any caching options. Using fetch inside a route handler should cache the request from what I've learned. The route handler is in path: /api/reviews/[tourId]/toute.ts

import { NextRequest, NextResponse } from "next/server";
import { URL } from "url";
/**
 * This function fetches reviews base don tourId. By defualt 5 tours are fetched per page,
 * The next page can be requested sing page searchParam
 */
export async function GET(
  req: NextRequest,
  { params }: { params: { tourId: string } }
) {
  try {
    const url = new URL(req.url);
    const page = `${url.searchParams.has("page") ? "&page=" + url.searchParams.get("page") : ""}`;
    const promise = await fetch(
      `${process.env.API_URL}/tours/${params.tourId}/reviews?limit=5${page}`
    );
    const res = await promise.json();
    return NextResponse.json({ ...res });
  } catch (err: any) {
    return NextResponse.json({ err: err.message, status: "fail" });
  }
}

I have a server action that posts a review to the database. I want to revalidate the cache of reviews so that I can refetch them with the new data. I am not sure about the usage of revalidatePath. Here is the server action:

export async function postReview(data: string): Promise<ServerActionRes> {
  try {
    //destructuring ensures that only required data in passed to the API
    const review: Review = JSON.parse(data);
    const isLoggedIn = cookies().has("session");

    //Check if the user is logged in and has a valid JWT cookie
    if (!isLoggedIn) throw new Error("User not logged in!");
    const token = cookies().get("session")?.value;
    if (!token) throw new Error("Invalid session cookie. Please login again");

    //send a post reuqest to post a new review
    const promise = await fetch(
      `${process.env.API_URL}/tours/${review.tourId}/reviews`,
      {
        method: "POST",
        headers: {
          "Content-type": "application/JSON",
          Authorization: `Bearer ${token}`,
        },
        body: JSON.stringify(review),
      }
    );

    const res = await promise.json();
    if (res.status === "fail") throw new Error(res.err);
    revalidatePath("/api/reviews/"); //is  it the correct way to do it?
    return { status: "success", data: null, error: null };
  } catch (err: any) {
    return { status: "fail", data: null, error: err.message };
  }
}

In development mode I did not see any changes even if I included the revalidatePath in serveraction.

Upvotes: 0

Views: 67

Answers (0)

Related Questions