fetch data with sort not updating after build

65 views Asked by At

I'm trying to fetch data from MongoDB with sorting. It works fine in dev server but not updating data after build(hosted)

import Review from "@/models/review";
import connectdb from "@/util/mongodb";
import { NextResponse } from "next/server";

export async function GET (){
    await connectdb();
    const reviews  = await Review.find().sort({ createdAt: -1 }).select("_id title category rating image episodes").limit(6).exec();
    return NextResponse.json({data:reviews});
}

Here when I build server on vercel it fetches & sorts data the first time but when the user adds new data, then this get should fetch new data too & display them on top but it's not working.

(for information, I used this on Next.js 14 app dir. & this called on homepage)

This is the controller:

export default async function getLetestReview() {
    try {
      const api = process.env.API_URL;
      const response = await fetch(`${api}/api/homepage`,      
      {
        cache: "no-store",
      });
      
      const reviews = await response.json();
      return reviews.data;
    } catch (error) {
      console.log(error);
    }
  }
import Review from "@/models/review";
import connectdb from "@/util/mongodb";
import { NextResponse } from "next/server";

export async function GET (){
    await connectdb();
    const reviews  = await Review.find().select("_id title category rating image episodes").limit(6).exec();
    return NextResponse.json({data:reviews});
}

I removed sort then it works fine & fetches data as expected (of course not sorting so it displays in default order but when I remove the 1st data then it reflected)

But, in the end I need sorting so please help me.

1

There are 1 answers

0
Khalif On BEST ANSWER

Using cache: "no-store" is a good practice, but sometime you can face the caching and it could happen when you try to fetch the data in the client side rendering, to make sure the data is fetched in each request to fetch data in such that case use server side rendering or you can add some unique parameter to API to force a fresh request like this

const response = await fetch(`${api}/api/homepage?timestamp=${new Date().getTime()}`, {
  cache: "no-store",
});

or you can add instead of cache revalidate

{
    next: {
        revalidate: 3600,
    },
}

or instead of both cache and revalidateyou can addforce-dynamic` before the component function to force the route to refetch every request and not cache it.

export const dynamic = "force-dynamic";