1

I have created a demo meetup NextJS application and deployed it on Vercel. It works perfectly fine on localhost and on Vercel server as well.

But problem I am facing is that I am not able to fetch the latest record from the MongoDB database.

Let me explain with the example: I have a form which is used to upload/insert the data on MongoDB collection. It is inserting properly on DB and after inserting on the client side (NextJS side) I am redirecting to the home page where I am fetching data from MongoDB using "getStaticProps".

On home page after redirecting I am not able to see latest inserted record. I have to do some changes on the code and need to push it and after doing redeployment it is showing me the latest record. I guess this is not the right way to achieve latest record.

Am I mistaken somewhere?

5
  • Hey there can you show some screen shots so i can see what really happens Commented Aug 22, 2022 at 10:13
  • if you'll push your code to GitHub then vercel will automatically re-deploy your app Commented Aug 22, 2022 at 10:14
  • @zainuldin screenshot regarding what? I am not getting the latest inserted record from mongodb database on the vercel but it is showing perfectly on the localhost. Commented Aug 22, 2022 at 10:15
  • please check changes happen in your repo or not? Commented Aug 22, 2022 at 10:16
  • Yes. Changes are there in repo. Commented Aug 22, 2022 at 10:18

2 Answers 2

3

You are using getStaticProps, which generates your HTML structure on build. This way, your app is not updating its data whenever they change. It works locally in development mode because getStaticProps is "disabled" in this mode (it runs on every request, essentailly becoming getServerSideProps). Try using getServerSideProps instead.

Sign up to request clarification or add additional context in comments.

1 Comment

Oh! Yes. By using getserversideprops it worked. Thank you
0

I was facing the same problem with my app and the below thing worked for me. You can give it a try by adding the 'revalidate' in your routes or API file (wherever you are connecting to the database and trying to fetch the data).

export const revalidate = 0;

One sample of my code is below:

import connectMongoDB from "../../../lib/mongodb";
import User from "../../../../models/user";
import { NextResponse } from "next/server";

export const revalidate = 0; // This is the new line added

export async function GET()  {
    await connectMongoDB();
    const users = await User.find();
    return NextResponse.json({users});
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.