#I have modified some data in my DB, but getStaticProps() isn't updating it

113 messages · Page 1 of 1 (latest)

torn venture
#

Hello,

my Nextjs version is 13.2.1, earlier I was using SSR, now I am trying to utilize the ISR (getStaticProps()), and I have made some little changes in the DB and I am making an /pages/api call from the getStaticProps() but the updated content isn't updating when running npm run build and if I am trying npm run dev then after few mins it's reflecting but not when npm run build & npm run start

/pages/api/common/blogs/all.jsx:

// DB Config
import { connectDatabase, disconnectDatabaseConnection } from '../../../../DB/MongoDBQueries/connection'

// Queries
import { getAllDataByCondition } from '../../../../DB/MongoDBQueries/common'

// CONSTANTS
import { API_END_POINT_NOT_FOUND, DATABASE_CONNECTION_FAILED, SOMETHING_WENT_WRONG, UNSUCCESSFUL_MESSAGE } from '../../../../constants'

const handler = async (req, res) => {
  // res.setHeader('Cache-Control', 's-maxage=86400')

  let client

  try {
    client = await connectDatabase()
  } catch (error) {
    res.status(500).json({ message: DATABASE_CONNECTION_FAILED })
    throw new Error(error)
  }

  try {
    if (req.method === 'GET') {
      try {
        const blogsData = await getAllDataByCondition(client, 'blog', { isDeleted: false }, { publishedDate: -1 })

        if (blogsData) {
          return res.status(200).json({ payload: blogsData })
        }
        return res.status(400).json({ payload: UNSUCCESSFUL_MESSAGE })
      } catch (error) {
        console.log(' -----------------------------------------')
        console.log('file: all.jsx:33 ~ handler ~ error:', error)
        console.log(' -----------------------------------------')
        return res.status(500).json({ payload: SOMETHING_WENT_WRONG })
      }
    }
    return res.status(404).json({ payload: API_END_POINT_NOT_FOUND })
  } catch (error) {
    return res.status(500).json({ payload: SOMETHING_WENT_WRONG })
  } finally {
    await disconnectDatabaseConnection()
  }
}

export default handler
humble talonBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

      🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in <id:customize>

      ✅ You can mark a message as the answer for your post with `Right click -> Apps -> Mark Solution`
      (if you don't see the option, try refreshing Discord with Ctrl + R)
torn venture
#

and below is the /pages/blogs.jsx - getStaticProps code:

export const getStaticProps = async () => {
  try {
    const resp = await serverSideAxiosInstance.get('/api/common/blogs/all')
    console.log('resp => ', resp.data)

    return {
      props: {
        blogs: resp.data.payload,
      },
    }
  } catch (error) {
    return {
      notFound: true,
    }
  }
}
#

can anybody help me why it's happening this way?

obsidian jacinth
#

in the api route where you update the db, or in any api routes basically, await res.revalidate("/blogs")

torn venture
#

okay!

#

also suppose, if I am creating/adding new blog post, the above await res.revalidate("/blogs") will add the newly add blog to the blogs page & single blog page? or I've to re-run npm run build?

obsidian jacinth
#

then it should work

#

see the link above for more info, they explain it in a lot of details

torn venture
obsidian jacinth
#

no need to rerun yes

#

although for getStaticPaths i'm not entirely sure

#

you probably need to fallback: "blocking" or something to disable 404 for non-existent routes

#

then return notFound for truly non existent routes in getStaticProps

#

then res.revalidate will probably work

#

but i'm not sure really – the best way to know is to just play with it

#

run res.revalidate("/any/path") and see if it works

torn venture
#
export const getStaticPaths = async () => {
  try {
    // Fetch the dynamic data to create paths for each project
    const resp = await serverSideAxiosInstance.get('/api/common/blogs/all')
    const blogs = resp.data.payload

    // Create an array of paths with the `slug` parameter
    const paths = blogs.rows.map(blog => {
      return { params: { slug: blog.slug } }
    })

    return {
      paths,
      fallback: false, // If fallback is set to false, any paths not returned by getStaticPaths will result in a 404 page.
    }
  } catch (error) {
    console.error('Error while generating paths:', error)
    return {
      paths: [],
      fallback: false,
    }
  }
}

this is my current /blog/[slug].js page where I am using this getStaticPaths()

#

@obsidian jacinth

obsidian jacinth
#

if it doesn't work, use fallback: "blocking" and it should probably work

obsidian jacinth
#

yeah

torn venture
# obsidian jacinth yeah

so total there'll be 2 revalidate call

await res.revalidate('/blogs')
await res.revalidate('/blog/new-slug-name')
obsidian jacinth
#

yeah

torn venture
# obsidian jacinth yeah

from the Postman, 3 hours ago I've added a blog, but bymistake instead of array I passed the string, then I manipulated directly in the MongoDB, now I deleted the Dummy Blog Post, but still npm run build is throwing the error for it

#

any help to avoid it?

obsidian jacinth
#

if db is correct then npm run build shouldnt complain

torn venture
#

yes

obsidian jacinth
#

though you can remove the .next folder to clear all cache

#

and try to rebuild again

torn venture
#

I deleted the .next folder, then tried running npm cache clean -f

#

still the same error

torn venture
obsidian jacinth
#

what error?

torn venture
#

this is the rror

#

/blog/blog-title here the /blog-title that's a new post I had added few hours ago, but it's not completely deleted from the DB

#

and when running npm run dev there it's working correctly

obsidian jacinth
#

ah yeah you need to check that the blog actualy exists inside getStaticProps as well

#

what do your getStaticPaths and getStaticProps currently look like

torn venture
#
export const getStaticProps = async context => {
  try {
    const { slug } = context.params

    const resp = await serverSideAxiosInstance.get(`/api/common/blogs/${slug}/details`)

    return {
      props: {
        blog: resp.data.payload,
      },
    }
  } catch (error) {
    return {
      notFound: true,
    }
  }
}

// Add getStaticPaths function here
export const getStaticPaths = async () => {
  try {
    // Fetch the dynamic data to create paths for each project
    const resp = await serverSideAxiosInstance.get('/api/common/blogs/all')
    const blogs = resp.data.payload

    // Create an array of paths with the `slug` parameter
    const paths = blogs.rows.map(blog => {
      return { params: { slug: blog.slug } }
    })

    return {
      paths,
      fallback: false, // If fallback is set to false, any paths not returned by getStaticPaths will result in a 404 page.
    }
  } catch (error) {
    console.error('Error while generating paths:', error)
    return {
      paths: [],
      fallback: false,
    }
  }
}
torn venture
obsidian jacinth
#

I mean thing like this basically

// pages/blogs/[slug].tsx
import {
  GetStaticPathsResult,
  GetStaticPropsContext,
  GetStaticPropsResult,
} from "next";

export async function getStaticPaths(): Promise<GetStaticPathsResult> {
  const allBlogs = await getAllBlogs();
  return {
    paths: allBlogs.map((blog) => ({ slug: blog.slug })),
    fallback: "blocking",
  };
}

export async function getStaticProps({
  params,
}: GetStaticPropsContext): Promise<GetStaticPropsResult<{ title: string }>> {
  const blog = await getBlog(params.slug);
  if (!blog) return { notFound: true };
  return { props: { title: blog.title } };
}
torn venture
#

I am not using Typescript, I am using pure JS

obsidian jacinth
#

yeah then remove the type annotations

#
// pages/blogs/[slug].jsx
export async function getStaticPaths() {
  const allBlogs = await getAllBlogs();
  return {
    paths: allBlogs.map((blog) => ({ slug: blog.slug })),
    fallback: "blocking",
  };
}

export async function getStaticProps({ params }) {
  const blog = await getBlog(params.slug);
  if (!blog) return { notFound: true };
  return { props: { title: blog.title } };
}
torn venture
#

still the error remains same 😢

obsidian jacinth
#

where is blog[0].tags.map used

#

most likely blog[0].tags is undefined or null

torn venture
#

that's the issue, the 3 blogs have tags as an array, and the 4th Dummy Blog I've added earlier it was as string later I modify directly in the DB, then I deleted it as well

#

but still it's stuck to it whereas in the DB it doesn't exists

obsidian jacinth
torn venture
#

but the entire entry in the DB is deleted, not only tags but the entire Entry of that blog is deleted now

obsidian jacinth
#

then why do you still get it in the getStaticPaths?

#

const resp = await serverSideAxiosInstance.get('/api/common/blogs/all')

this part still returns the removed item

#

so it is buggy

#

check it

torn venture
#

but when I am running npm run dev, both /blogs & /blog/[slug] is working correctly fine

#

and in npm run dev in /blog/[slug] I consoled the the following:

const resp = await serverSideAxiosInstance.get('/api/common/blogs/all')
    const blogs = resp.data.payload
    console.log({ blogs })

the output I got is { blogs: { count: 3, rows: [ [Object], [Object], [Object] ] } }

#

so I don't think it's a buggy

obsidian jacinth
torn venture
#

yes

#

it's in /pages/api/common/blogs/all

obsidian jacinth
#

then how does it even work during build, when the api routes are not running?

#

i'm quite surprised, it should say something like invalid url or fetch failed

obsidian jacinth
torn venture
obsidian jacinth
torn venture
#

and also, the DB remains same,

obsidian jacinth
#

so idk what's happening here

torn venture
#

yes, that's where I am wondering as well, why npm run build for ISR is not updating even when I've deleted the entry from DB & as well as deleted the .next folder

#

@obsidian jacinth what to do on this?

obsidian jacinth
#

idk what happens here so cant help, sorry

torn venture
obsidian jacinth
torn venture
obsidian jacinth
#

Not too relevant to SEO imo, though UX is significantly enhanced

obsidian jacinth
torn venture
#

okay

obsidian jacinth
#

You load a website, then if it loads instantly it is better than if it loads in 1s

torn venture
#

I thought Blogs pages and all relevant with ISR will be build at build-time only, so the web page will load faster then it can help the SEO as well

obsidian jacinth
#

Yes, SSG/ISR is ideal for blogs. Idk about this particular case though since idk why that error happens

torn venture
#

@obsidian jacinth

I just tried using res.revalidate('/works'), which is using ISR, and I just tried to update it using Postman by calling my API, but the /works/ page didn't got updated as it've only getStaticProps()

obsidian jacinth
torn venture
#

ok

#

we can't use http://localhost:3000 in ISR/SSR, right? @obsidian jacinth

obsidian jacinth
#

@torn venture ping

obsidian jacinth
#

shhhhh is this site of yours open source

torn venture
obsidian jacinth
#

basically move the logic from your api routes to inside getstaticprops/getserversideprops

obsidian jacinth
#

based on your code

#

cuz idk how to explain it either

torn venture
#

actually I am using pure MongoDB, so I've to make connection first and then fetch the data

torn venture
# obsidian jacinth cuz idk how to explain it either

I got the issue, it seems that my Chrome Browser still have the cache, because https://dhavalvira.com/api/common/blogs/all this when I am accessing it from my Chrome, I'm still having that data, and to cross verify I checked in my Mobile, but it's not there, but it's weird thing for me

obsidian jacinth
torn venture
#

res.setHeader('Cache-Control', 's-maxage=86400')

this line is there in /pages/common/blogs/all API End Point

#

@obsidian jacinth

obsidian jacinth
#

no let's just put it this way. i have zero idea what is happening, and from the information you provided i cannot see anything of worth to tell you, so i cannot help you here. sorry about that