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

Error encountered while compiling NextJS: Unexpected use of single quotation mark in jsx-quotes

I can't seem to compile my NextJs 13 app without encountering errors. Take a look at my shortened eslintrc.js file below: module.exports = { env: { browser: true, es2021: true, }, extends: [ 'plugin:react/recommended', ...

Ways to create two distinct "on click" actions for a single image to execute two distinct tasks

Clicking on an image will open a slider showing all images before filtering. Once filtered, only the selected images will be displayed in the slider. <div class="gallery row" id="gallery" style="margin:0;"> <!-- Grid column --> <div ...

Moment.js generated an error due to an unhandled promise rejection warning

I'm trying to determine if my current timestamp is equal or greater than a certain value, but I keep encountering errors. Here's my code with the error: {...} exports.validaforgotpass = async (req, res) => { {...} const results = aw ...

best way to eliminate empty p tags and non-breaking spaces from html code in react-native

How can I clean up dynamic HTML content by removing empty <p> tags and &nbsp? The whitespace they create is unwanted and I want to get rid of it. Here's the HTML content retrieved from an API response. I'm using the react-native-render ...

The process of parsing HashMap failed due to an unexpected encounter with an Array, when an Object

Currently, I am in the experimental phase of creating an action at Hasura using a Node.js code snippet hosted on glitch.com. The code snippet is as follows: const execute = async (gql_query, variables) => { const fetchResponse = await fetch( "http ...

Could one potentially use PHP to automatically update the database at specified intervals?

Let's say we have a table structured like this: Activities: id start_time status Now, I want to insert an activity starting on 2013-01-01, with a status of 0. If the server reaches 2013-01-01, the status should automatically change to 1. I could cr ...

Having trouble resolving the "next-head-count is missing error"?

Although I've seen similar questions before, none of the solutions worked for me. Here is my code snippet: //_document.tsx import Document, { Html, Head, Main, NextScript } from "next/document"; export default class MyDocument extends Docum ...

How can I declaratively bind the properties in Dojo's _hasDropDown method?

UniqueSearchComponent.html: <div class="${baseClass}"> <div data-dojo-type="dijit/_HasDropDown" data-dojo-props="dropDown: 'containerNode'"> <div data-dojo-type="dijit/form/TextBox" name="${SearchViewFieldName} ...

Uploading files in React.js using Yii2 API

I am working with react.js (version 15) and I need to upload files using yii2 api. Here is my code: My component in react: import React, { Component } from 'react'; import Header from './Heaader'; /* global $ */ class New ...

Tips for deploying uploadthing on Vercel for my upcoming Next.js project

After deploying my file uploader (using uploadthing) to vercel, I encountered an issue where I did not receive a response. The error message I received was: [UT] Call unsuccessful after 4 tries. Retrying in 8 seconds... I tried to find information in the ...

ASP.NET repeater causing jQuery scrollTop to malfunction after first use

I am facing a peculiar issue where I need to scroll through repeater items in a RadWindow using arrow keys in an ASP.NET application. Below is the code snippet: function isScrolledIntoView(elem) { var docViewTop; var docViewBottom ...

The download of package-lock.json is not initiated for a linked GitHub URL

I currently have two projects on GitHub. One is named "mylibrary" and the other is "test-project." In my "test-project," I have linked "mylibrary" using its GitHub URL in the package.json file as shown below. dependencies: { "mylibrary": "git+ssh://& ...

What is the best way to eliminate an object from an array of objects depending on a certain condition?

I have an array of objects structured like so: data = [ { "name":"abc", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa9b9899ba9d979b9396d4999597">[email protected]&l ...

JavaScript Application - Problem with Universal Windows Script

I recently built a website utilizing material design lite for the aesthetics: Here are the scripts included: <script src="./mdl/material.min.js"></script> <script src="Scripts/angular.min.js"></script> The necessary .css fi ...

Generating a dynamic clickable div using Angular 6

How can I create a user-friendly interface that displays an image with clickable divs around detected faces, allowing users to view specific attributes for each face? I'm looking for a solution where I can have divs or buttons around each face that t ...

Execute a multer request to upload an image (using javascript and express)

I am utilizing the Express server as an API gateway for my microservices, specifically to process and store images in a database. The issue at hand is that within the Express server, I need to forward an image received through a POST request from the clien ...

(NodeJS + Socket IO Issue) NodeJS is sending duplicate data when the page is refreshed, causing an improper response

Each time I refresh a page, NodeJS seems to be repetitively writing data on the socket. Interestingly, the number of writes increases with each page refresh but then stabilizes at three after several refreshes. I urge you to inspect the console output whi ...

Efficient methods for transferring information between a main and pop-up page within angularjs

On my webpage, I have a button that opens a popup page. I need to figure out a way to transfer json data from the main page to the popup page. These two pages are running separate angular applications. Once the data is transferred, it will be updated base ...

What is the best way to add a hyperlink to a cell in an Angular Grid column

I need help creating a link for a column cell in my angular grid with a dynamic job id, like /jobs/3/job-maintenance/general. In this case, 3 is the job id. I have element.jobId available. How can I achieve this? Here is the code for the existing column: ...

My JavaScript code is being executed before Chrome Auto-fill

I have successfully created form input elements in Chrome that display a floating label when focused. However, I am encountering an issue when the browser autofills the username and password fields with yellow prefilled text. The JavaScript for the float ...