Database records failing to update after deployment

After deploying my next js site using Vercel, I encountered an issue with the functionality related to adding, getting, editing, and deleting data from MongoDB. Although all functions were working perfectly locally, once deployed, I noticed that while I could still perform these actions on the database, the browser was only displaying old data that was added before deployment, failing to show any new data.

Despite seeing the changes reflected in the database itself, the updates were not being displayed on the screen. What could possibly be causing this discrepancy?

const [allProjects, setAllProjects] = useState([]);

// fetch all projects
  useEffect(() => {
    const fetchProjects = async () => {
      const res = await fetch("/api/project", {
        cache: "no-cache",
        headers: {
          "Cache-Control": "no-cache",
        },
      });
      const data = await res.json();
      setAllProjects(data);
    };

    fetchProjects();
  }, []);

  console.log("allProjects: ", allProjects);

This is the API route:

/api/project/route.ts

export const GET = async (req) => {
  try {
    await connectToDB();
    const projectSchema = await Projects.find({}).populate("_id");
    return new Response(JSON.stringify(projectSchema), { status: 201 });
  } catch (error) {
    new Response("Failed to fetch Project", { status: 500 });
  }
};

Answer №1

Make sure to include the necessary API HTTP request headers

'Cache-Control': 'no-store'

Your browser may cache your response data. Prevent this by blocking caching.

Answer №2

Make sure to include the projects state in the dependency array so that the page can be re-rendered with the updated changes from the project state whenever it changes. I also suggest using react-query over useFetch as it is more suitable for your needs, especially with handling the loading and error states.

useEffect(() => {
    const fetchProjects = async () => {
      const res = await fetch("/api/project", {
        cache: "no-cache",
        headers: {
          "Cache-Control": "no-cache",
        },
      });
      const data = await res.json();
      setAllProjects(data);
    };

    fetchProjects();
  }, [projects]);

  console.log("allProjects: ", allProjects);

If the projects is an object, remember to use the useMemo hook to ensure that the reference of the object remains consistent:

const cachedProjects = useMemo(() =>({projects}), [projects])
useEffect(()=>{
// same code as above
}, [cachedProjects])

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

Angular 2: Shared functions for universal component usage

I am working on an Angular 2 webpack project and I have come across a scenario where I have some functions that are repeated in multiple components. I want to find a way to centralize these functions in a "master" class or component so that they can be eas ...

Experiencing a problem with value formatting while attempting to implement tremor for charts in React with Next.js version 13

import { getAuthSession } from "@/lib/auth"; import { db } from "@/lib/db"; import { Card, LineChart, Text, Title } from "@tremor/react"; import Linechart from "./LineChart"; const dollarFormatter = (value: number) ...

Dynamic starting point iteration in javascript

I'm currently working on a logic that involves looping and logging custom starting point indexes based on specific conditions. For instance, if the current index is not 0, the count will increment. Here is a sample array data: const data = [ { ...

A guide on parsing a stringified HTML and connecting it to the DOM along with its attributes using Angular

Looking for a solution: "<div style="text-align: center;"><b style="color: rgb(0, 0, 0); font-family: "Open Sans", Arial, sans-serif; text-align: justify;">Lorem ipsum dolor sit amet, consectetur adipiscing e ...

Issue with React component not updating content after state changes in Next.js framework

Currently, I am facing an issue with my Header component not updating its content on state change. The goal is to show the user's Profile once the state changes, but unfortunately, it does not update immediately; it only changes after a page refresh o ...

Is there a way to implement several filters on an array simultaneously?

Is it possible to filter an array based on both the input text from the "searchTerm" state and the selected option from the dropdown menu? I am currently using react-select for the dropdown functionality. const Positions = ({ positions }: dataProps) => ...

What could be the reason for one function returning undefined from identical API calls while the other functions produce successful results?

As I delved into incorporating the TMDB API into my project, a perplexing issue arose that has left me stumped. Despite utilizing identical code snippets in two separate files and functions, one of them returns undefined while the other functions flawlessl ...

Glitch causing incorrect images to appear while scrolling through FlashList

Currently, I am using the FlashList to showcase a list of items (avatars and titles). However, as I scroll through the list, incorrect images for the items are being displayed in a mixed-up manner. Based on the explanation provided in the documentation, t ...

Error: The specified type 'OmitWithTag<GetServerSidePropsContext<ParsedUrlQuery>, keyof PageProps, "default">' does not meet the requirements of '{ [x: string]: never; }'

While my app works in dev mode, it crashes when I try to run the build command. The output of npm run build is as follows: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5dbd0cdc198d4c5c598c1d0d8c5d9d4c1d0f5859b859b84"&g ...

Is it advisable to utilize TypeScript interfaces for declaration files and React component prop definitions?

Whenever I create structures for object types, my go-to method is to define them in my declaration.d.ts file like this: type TagsObject = { _id: string; tag: string; } type ProjectData = { _createdAt: string; _id: string; _rev: string; _type: ...

Customizing the Android Back Button behavior in NativeScript for a single specific page

I am currently using NativeScript version 5.2.4 along with TypeScript. My goal is to disable the back button functionality in one specific page only, but I'm facing an issue where it also disables the back button behavior for child pages. Below is the ...

Promise rejection not handled: The play() function was unsuccessful as it requires the user to interact with the document beforehand

After upgrading my application from Angular 10 to 11, I encountered an error while running unit tests. The error causes the tests to terminate, but strangely, sometimes they run without any issues. Does anyone have suggestions on how to resolve this issue? ...

What is the best way to determine Prisma types across various projects?

My current project has the following structure: dashboard -- prisma-project-1 -- prisma-project-2 -- client-of-prisma-project-1-and-prisma-project-2 This dashboard is designed to merge data from two separate databases and display them in a meaningful w ...

Passing data to a server-side component in Next.js: a guide

I am working on a website dedicated to dynamic blogs and I need to pass parameters to an API URL in order to retrieve a specific blog. However, I must ensure that the approach I take does not hinder SEO by utilizing local storage, cookies, or any other c ...

Leverage the keyof operator for automatic determination of return type

My interface looks like this: interface ResourceState<ItemType> { rows: ItemType[], store: Record<String, ItemType> } To create a root state, I use the following structure: RootState{ car: ResourceState<Car> user: ResourceState<User&g ...

What is the correct way to implement strong typing for a reactive array consisting of interface Class objects in TypeScript?

My goal is to develop a dynamic array that can store data fetched from a database through an HTTP request using a SQL query. Since I lack direct access to the database, my only option is to submit a query to retrieve the required information. The retrieved ...

Angular loop is unable to detect changes in the updated list

My Angular application is facing a peculiar issue that I can't seem to figure out. // Here are the class attributes causing trouble tenants: any[] = []; @Input() onTenantListChange: EventEmitter<Tenant[]>; ngOnInit(): void { this. ...

How to remove a variable definition in Typescript

Is there a way to reset a variable to undefined after assigning it a value? To check, I am using the Underscore function _.isUndefined(). I have attempted both myVariable = undefined and delete myVariable without success. ...

What is the method to cancel a server action in Next.js?

Visit the Next.js documentation on server actions The documentation does not provide information on how to abort an action or handle abortions. ...

What is the best way to compare an array with comma-separated values in JavaScript?

I have a scenario where I have two arrays, one for categories and the other for products. Each product contains multiple categories as a comma-separated string. My goal is to match a specific category with each product's product_category value and the ...