Production website fails to display updated data while the localhost version operates without issues

Having trouble fetching data from my database in a production setting. The code functions fine on localhost, but fails to grab updated data when live. Below is the relevant snippet:

import {connect} from "@/dbConnection/dbConnection";
import Post from "@/modals/postModal";

export const GET = async () => {
    console.log('Request Made on Get Posts...' );
    try{
        await connect();
        const posts = await Post.find().sort({createdAt: -1}).limit(20);
        if(!posts){
            return Response.json({error: "Posts not found"});
        }
        return Response.json({posts});

    }catch (e) {
        return Response.json({error: "Database error"});

    }
}

Data retrieval code :

const [posts, setPosts] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    useEffect(() => {
            setLoading(true)
            setTimeout(
                () => {
                    fetchPosts().then((r) => {
                        setPosts(r.posts)
                        setLoading(false)
                    }).catch((e) => {
                        setError("Error fetching posts")
                        setLoading(false)
                    });
                }
                , 2000
            )


        }
        , []);

    async function fetchPosts() {

        try {
            const response = await axios.get('/api/post/getblogs');
            return response.data;

        } catch (error) {
            setError("Error fetching posts")
        }

    }

Production link :

Visit here

Steps taken:

Confirmed correct database connection setup. Verified functionality on localhost with success. Checked logs for any issues, but no errors were found.

Expected outcome:

Upon requesting post data, the code should retrieve the most recent information from the database.

Answer №1

The issue stemmed from the browser potentially caching the backend route's response, causing repeated retrieval of the same data without querying the server again.

Updated Implementation

import {connect} from "@/dbConnection/dbConnection";
import Post from "@/modals/postModal";

// Retrieve all posts

async function handler (request) {
    console.log('Request Made on Get Posts...' );
    const newHeaders = new Headers(request.headers);
    newHeaders.set('Cache-Control', 'no-cache');

    try{
        await connect();
        const posts = await Post.find().sort({createdAt: -1}).limit(20);
        if(!posts){
            return Response.json({error: "Posts not found"});
        }
        return Response.json({posts});

    }catch (e) {
        return Response.json({error: "Database error"});

    }
}



export {handler as GET}

By specifying the Cache-Control header as no-cache, it directs the browser to refrain from caching the response, ensuring that fresh data is retrieved from the server upon each request to the endpoint.

Answer №2

export const FETCH_POSTS = async () => {
console.log('Fetching Posts...');
try {
    await connect();
    const posts = await Post.find().sort({ createdAt: -1 }).limit(20);
    if (posts.length === 0) {
        return Response.status(404).json({ error: "Posts not found" });
    }
    return Response.status(200).json({ posts });
} catch (e) {
    console.error(e);
    return Response.status(500).json({ error: "Database error" });
}

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The position of a jQuery element gets reset when both the show and stop animations are used

When I use jQuery's .position() to place an element, everything works fine. But as soon as I display an animation and then cancel it with an ajax call, the position of the element resets. function displayMessage(msg) { var $messageEl = $('#u ...

Excluding Layout from Display on Certain Pages in a Next.js 13 App Router

I am currently working on a personal project that involves using the Next.js 13 app router, and I have encountered a dilemma. Within my project, there is a header component injected into the layout.tsx file located in the root directory. However, I also ha ...

Issue Detected at a Precise Line Number - Android Studio

Despite my numerous attempts to modify the specific line in question, including leaving it empty, turning it into a comment, or removing it entirely, the error message persists. I even went as far as deleting the class and creating a new one, but the same ...

Is there a way to include a lockfile in a docker container as an optional step?

I am attempting to create a docker image that can optionally incorporate a yarn or npm lockfile during the build process. I want to include it explicitly, but also ensure that the build does not fail if the lockfile is missing. The goal is to respect dete ...

JavaScript and CSS failing to implement lazy loading with fade-in effect

Is there a way to add the fade-in animation to an image when it is loaded with JavaScript or CSS? Currently, the code I have only fades in the image once it is 25% visible in the viewport. How can I modify it to include the fade effect upon image load? ...

The basic node API request is not showing any information

There is a request in my server.js file var Post = require('./../models/post'); //GET ALL POSTS app.get('/api/posts', function (req, res) { Post.getPosts(function (err, posts) { if(err) { throw err; } ...

"Effortless Auto-complete with Linked Content and Visuals

I've been searching everywhere and have not been able to find a solution for this issue. I can successfully use JQuery Easyautocomplete () with links, and also with images separately, but I can't figure out how to make it work with both. I am new ...

Angular.js encountered an error at line 13550: [ng:areq] The argument 'popCntrl' is expected to be a function, but it was undefined

I have been diving into learning AngularJS on my own recently, and I've been attempting to create a basic popup feature. However, I keep encountering the error mentioned in the title. While searching for solutions, I haven't found any examples th ...

Having trouble with Nextjs not rendering as expected and displaying a "Warning Prop `style` did not match" error when using inline styles?

Issue Description I'm encountering a problem with my nextjs application. I need to apply different styles/classNames to certain components based on whether they are rendered on the client-side or server-side. Below is a simplified demonstration code ...

Looking for advice on utilizing Node.js and MongoDB to identify platform modifications on a website

I need guidance for a project I'm currently working on. The project involves extracting headers, like the example below in Mongo document format: { "url": "google.com", "statusCode": 301, "headers": { "location": "http://www.goog ...

Preserve the existing value and then check it against the updated value of a variable within JavaScript

I utilized an API that supplies me with information in JSON format, retrieved the price of a specific currency, and presented it on a screen using JavaScript. I encapsulated this process within a function that dynamically updates the information at set int ...

I'm experiencing trouble with Shopify as it appears to be failing to execute

I have been attempting to incorporate a tracking pixel into my project. Thus far, I have tested the code in various environments, both with and without wrapping it in a function and deploying it using window.onload. If you would like to see the implementa ...

Develop a React.js script that enables the addition of a new question

As I work on creating a script to incorporate Q&A functionality in react.js and mongodb, I'm facing an issue wherein pressing a button triggers the following errors: Error: Cannot POST /create Status: 404 (Not Found) When examining my code, I a ...

Can you explain the distinction between nextjs and nuxtjs?

Greetings! As I delve into a new project, I stumbled upon next and nuxtjs. I am curious about the advantages of incorporating either of them into my project. Can you shed some light on this? ...

Calculating the mean value of items in an ArrayCollection using Symfony and MongoDB

In my news class, I have ratings submitted by users. My goal is to calculate the average of all the ratings using MongoDB. Despite searching for a built-in function for averaging, I couldn't find one. So, I decided to utilize the count() function to d ...

One potential solution is sending a message to a user via a server using JavaScript on Node.js

Hey there, I've encountered a minor issue and would appreciate your help. Recently, I developed a weather program in NodeJs where users can search for the weather in their city. However, I'm facing a challenge with displaying the weather data to ...

What is the process for the Rebol programming language to independently implement an asynchronous pluggable protocol for reading

This post outlines the process of incorporating an asynchronous pluggable protocol in Rebol that can be accessed through Firefox, Internet Explorer, or the command line For instance, if I were to define the reb:// protocol, I could enter it into a browser ...

What is the best way to recover past messages from a channel?

I am working on a bot that is supposed to be able to retrieve all messages from a specific server and channel upon request. I attempted to use the channel.messages.cache.array() method, but it only returned an empty array []. How can I efficiently fetch ...

The installation of npm modules is failing with the error message: "'react-scripts' is not recognized as a valid command, internally or externally."

As I revisited my old project on GitHub, things were running smoothly a few months prior. However, upon attempting to npm install, I noticed the presence of the node modules folder and encountered some npm errors. https://i.stack.imgur.com/awvjt.png Sub ...

Utilizing Vue.js for the selection of multiple elements

I am currently in the process of transitioning from jQuery to Vue, and I have encountered an issue when trying to select multiple elements within a single Vue instance. For instance, On my website, there are two posts each with a comment form. I want to ...