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

Changing dot notation to bracket notation in Angular

Having trouble using dynamic columns in a Primeng table? The column fields need to be in bracket notation for this setup. What if you have a column with nested JSON structure and you're not sure how to write that in bracket notation? Don't worry, ...

Convert a regular element into a DebugElement within an Angular framework

Recently, I was working on testing an Angular Component which was going smoothly until I encountered a challenging issue that has been perplexing me for days. My main objective was to test whether the method "ajouterCompteurALaCampagne" is being called whe ...

Having trouble with React state not updating?

Hello, I am a beginner in the world of React and currently working on fetching an array of endpoints. My goal is to update the API's status every 15 seconds. Here is the code snippet for the array of endpoints: export const endpoints: string[] = [ " ...

Having trouble getting tailwind dark mode to work on next.js?

I have set up a custom boilerplate using next.js(10.0.5) with preact(10.5.12), typescript(4.1.3), and tailwind(2.0.2). I am attempting to incorporate a dark mode feature from Tailwind. I followed the instructions from next-themes in order to add the dark ...

Combining Rxjs map and filter to extract countries and their corresponding states from a JSON dataset

I have a unique dataset in JSON format that includes information about countries and states. For example: { "countries": [ { "id": 1, "name": "United States" }, { "id": 2, "name": "India" }], "states": [ { ...

Properly configuring paths in react-native for smooth navigation

When working on my React-Native project, I noticed that my import paths look something like this: import { ScreenContainer, SLButton, SLTextInput, } from '../../../../../components'; import { KeyBoardTypes } from '../../../../../enums ...

How can I assign a type to an array object by utilizing both the 'Pick' and '&' keywords simultaneously in TypeScript?

As a beginner in TypeScript, I am looking to declare a type for an array object similar to the example below. const temp = [{ id: 0, // number follower_id: 0, // number followee_id: 0, // number created_at: '', // string delete_at: &ap ...

React Typescript does not support the use of React-Router

I'm currently working on a React app that utilizes Typescript. The React version is set to "react": "^16.9.0", and the React-Router version is "react-router-dom": "^5.1.2". Within my App.tsx file, the structure looks like this: const App: React.FC ...

Customize Angular Material's Mat-Dialog background blur/darkening effect

Greetings, dear community members, I am currently utilizing angular along with angular material in my projects. By default, when a material dialog is opened, it slightly darkens the background. However, I am interested in having a blurred background inst ...

developing TypeScript classes in individual files and integrating them into Angular 2 components

We are currently putting together a new App using Angular2 and typescript. Is there a more organized method for defining all the classes and interfaces in separate files and then referencing them within angular2 components? import {Component, OnInit, Pi ...

Leveraging the Recyclability Aspect of a ReactJS Modal

Looking for a way to make a modal dynamic without duplicating too much code. Any suggestions on how to achieve this? I've managed to separate the state from the layout using render props. interface State { open: boolean; } interface InjectedMod ...

Sharing data between components with NextJS 14 and the app router: A guide

I am only 20 days into exploring Next.js, so there are probably some things I am missing. Right now, I have a dashboard page that is server side rendered and consists of 3 components. One of the components contains a button that, upon clicking, should upda ...

What could be causing my NodeJS Backend to not retrieve the data properly?

For a current project, I am tasked with building a mobile application using Flutter for the frontend and NodeJS for the backend. To facilitate this, I have acquired a VPS from OVHcloud running Ubuntu 20.04. Following various tutorials, I set up a server as ...

Prevent a React component from unnecessarily re-rendering after a property has been set

I am working on a react component that displays a streaming page similar to the one shown in this image. Here is a snippet of the code : const [currentStream, setCurrentStream] = useState<IStream>(); const [currentStreams] = useCollectionData<ISt ...

How can you generate a distinct id value for each element within an ngFor iteration in Angular 4?

I encountered an issue where I must assign a distinct id value to each data row within my *ngFor loop in angular 4. Here is the code snippet: <div *ngFor="let row of myDataList"> <div id="thisNeedsToBeUnique">{{ row.myValue }}</div> & ...

`Managing select tag data in Angular reactive forms`

Having an issue with selecting the gender option from JSON formatted data received from the backend. The gender is displayed as a select tag on the frontend, but it does not pre-select the option that corresponds to the gender value in the JSON data. The b ...

Mismatched data types caused by immutability

I'm having trouble with my object that has a middleware property and the types aren't working as expected. The error message is stating that the two middlewares are incompatible because one of them is set to readonly. Does anyone know how I can r ...

Exploring the potential of implementing dynamic routing at the root level in Next.JS

In my quest to establish routes for the root-level product page and product listing page in next.js, I find myself unsure about how it will function since everything within the route will ultimately lead to a route level file. The header navigation feature ...

The lib.dom.d.ts file is seriously lacking in many key components

Are there any updated versions of lib.dom.d.ts? The current one is missing a lot of essential information, causing numerous compilation errors. For example, consider this line: window.File && window.FileReader && window.FileList && ...

The type 'Bar<T>' cannot be assigned to type 'T extends number ? number | Bar<T> : Bar<T>'

I'm struggling with this particular code snippet: class Foo<T> { x?: T extends string ? string | Foo<T> : Foo<T> } function bar<T>(): Foo<T> { const x: Foo<T> = { } return { x } } Can anyone explain why the ...