Having trouble exporting constants and utilizing the "use server" function in actions.ts within Next.js?

I am currently developing an application using Next.js and I have a file called actions.ts where all my functions for fetching and adding data from my Vercel Postgres store are stored. After these functions, I want to revalidate the data so I included export const revalidate = 1 in order to achieve this. However, it seems that setting it to use server is also necessary because without it, @vercel/postgres cannot locate the CONNECTION_URL. The issue is that the revalidate variable does not work with use server.

What steps should I take?

Below is my code:

"use server"
import { sql } from "@vercel/postgres";
import { revalidatePath } from "next/cache";

export const revalidate = 1;
export async function fetchProjects() {
    const { rows } = await sql`SELECT * FROM projects`

    return rows
}

export async function fetchProjectById(id: string) {
    const { rows } = await sql`SELECT * FROM projects WHERE id = ${id}`

    return rows[0]
}

// Other functions omitted for brevity

export async function deleteMilestone(id: string, project_id: string) {
    await sql`DELETE FROM milestones WHERE id = ${id};`
        revalidatePath("/projects/[slug]")
}

An error occurs when trying to export constants while using use server. I am unsure of what actions to take as I require both functionalities in my code.

Answer №1

When implementing the use server directive, certain operations are restricted, such as directly exporting constants. In scenarios where server-side re-validation is required, a different approach must be taken. Here is a modified code snippet that can be utilized to achieve the desired outcome.

"use server";

import { sql } from "@vercel/postgres";
import { revalidatePath } from "next/cache";

// Function for retrieving the revalidate value
function getRevalidate() {
  return 1;
}

export async function fetchProjects() {
    const { rows } = await sql`SELECT * FROM projects`;
    return rows;
}

export async function fetchProjectById(id: string) {
    const { rows } = await sql`SELECT * FROM projects WHERE id = ${id}`;
    return rows[0];
}

export async function fetchProjectMilestones(id: string) {
    const { rows } = await sql`SELECT * FROM milestones WHERE project_id = ${id}`;
    return rows;
}

export async function createProject(title: string, description: string) {
    try {
        await sql`INSERT INTO projects (title, description) VALUES (${title}, ${description})`;
    } catch (error) {
        throw new Error("Failed to create new project.");
    }
}

export async function createMilestone(title: string, description: string, due_date: Date, project_id: string) {
    await sql`INSERT INTO milestones (title, description, due_date, project_id) VALUES (${title}, ${description}, ${due_date.toDateString()}, ${project_id})`;
    revalidatePath("/projects/[slug]");
}

export async function deleteMilestone(id: string, project_id: string) {
    await sql`DELETE FROM milestones WHERE id = ${id};`;
    revalidatePath("/projects/[slug]");
}

// Demonstration of how the revalidate function can be used.
export function exampleUsage() {
  const revalidateValue = getRevalidate();
  // Perform actions with revalidateValue here.
}

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

Creating click event handler functions using TypeScript

I encountered an issue when trying to set up an event listener for clicks. The error message I received was that classList does not exist on type EventTarget. class UIModal extends React.Component<Props> { handleClick = (e: Event) => { ...

Verify if the specified key is present in the type parameter and if it corresponds to the expected data type in the value parameter

I have a specific goal in mind: export interface GCLPluginConfig { [key: string]: string | number | boolean | Date | string[]; } export interface CorePluginConfig extends GCLPluginConfig { "core.lastUpdateCheck": Date; } export interface An ...

The updating of the page in Angular 4.4 is not reflecting the changes made to the model

After recently adding a new angular component to an existing codebase, I'm struggling to update the view with changes in the model due to my unfamiliarity with angular 4. Despite looking at similar questions, none of the solutions seem to work for me. ...

What could be causing the error message "Error: Failed to retrieve component for route: '/settings'" to occur in next js?

In my Next.js index file, I have incorporated the Next-Auth version 4 library. import React from 'react' import { useRouter } from 'next/router' import { useSession } from 'next-auth/react' import { Login } from '@/compon ...

I encountered the error message "The property you are trying to access does not exist on the type 'never'" while attempting to retrieve JSON data from the API response

Every time I attempt to access the fields in items such as id or title, an error pops up saying Property does not exist on type 'never'. Interestingly, when I log the data using console.log(response.data), everything seems to be working fine. I ...

Adding data to a join table with Sequelize

Among the tables we have are Users, Categories, and Users_Categories. Suppose we already have one user with user_id = 1 and one category with category_id = 1. Now, I am looking to establish a connection between them using the Users_Categories join table. ...

Tips for customizing the legend color in Angular-chart.js

In the angular-chart.js documentation, there is a pie/polar chart example with a colored legend in the very last section. While this seems like the solution I need, I encountered an issue: My frontend code mirrors the code from the documentation: <can ...

"What is the best way to access and extract data from a nested json file on an

I've been struggling with this issue for weeks, scouring the Internet for a solution without success. How can I extract and display the year name and course name from my .json file? Do I need to link career.id and year.id to display career year cours ...

Utilizing useLocation for Defining Text Styles

I'm currently integrating TypeScript into my project, but I'm encountering an error related to 'useLocation' in my IDE. Any thoughts on what might be causing this issue? import React from "react"; import { useHistory, useLocat ...

Implementing Dynamic Component Rendering in React Native with Typescript

For the past 3 hours, I've been grappling with this particular issue: const steps = [ { Component: ChooseGameMode, props: { initialValue: gameMode, onComplete: handleChooseGameModeComplete } }, { Com ...

Executing NestJS code after applying a pipe but before reaching the method handler

Is it possible to insert additional code after all the pipes have transformed but before the method handler is called? https://i.sstatic.net/IjQvv.png ...

Creating comprehensive and elaborate intellisense documentation for Typescript Union Types

When we call the baz function with the code provided, the typeahead will display 'a' and 'b' as potential values. https://i.stack.imgur.com/SrKo7.png If additional documentation is needed for each of these values, how can it be accomp ...

Error in Angular 7: ActivatedRoute paramId returns null value

On page load, I am trying to subscribe to my paramsID, but when I use console.log(), it returns null. I am currently working with Angular 7. Here is my TypeScript code: import { Component, OnInit } from '@angular/core'; import { Activat ...

Automatically selecting the country phone code based on the country dropdown selection

When the country dropdown is changed, I want the corresponding phone code dropdown to be dynamically loaded. <div class="row"> <div class="col-sm-8 col-md-7 col-lg-6 col-xl-5 pr-0"> <div class="form-group py-2"> <l ...

React-query v5 - Updating or fetching outdated query

I am currently using the Tanstack/react-query v5.12.2 library and I am facing an issue with invalidating or refetching an inactive query using the useQueryClient() function. It seems that something has changed in version 5 of the library. I have tried sett ...

Breaking a relation constraint due to deferred constraints on foreign keys

My goal is to ensure atomicity in my database by setting my SQL scripts into a transaction. The tables are structured like this (simplified): CREATE TABLE foo ( id serial NOT NULL, foo varchar(50) NOT NULL, CONSTRAINT foo_pk PRIMARY KEY ...

Passing parameters in React classes is a crucial aspect of creating

Within a project I am currently working on, there is a const defined for the page header which takes in parameters and utilizes the information: interface UserProps { user?: { name: string, image: string }, loading?: boolean, error?: E ...

Challenges when building a production version of an Expo app with Typescript

Attempting to perform a local production build, I ran expo start --no-dev --minify. Only the initial template file displays, stating "Open up App.tsx to start working on your app," and none of my work is visible... Has anyone else encountered this issue a ...

What steps should I take to fix the Typescript error showing up in my Next.js route?

import type { NextApiRequest, NextApiResponse } from "next"; import db from "../../app/libs/dbConn"; interface DataProps { auth: [ { name?: string; email?: string; passwordHash?: string; } ]; status: n ...

How can I prevent having to repeat the getStaticProps function on multiple pages within NextJS?

Navigating React/NextJS as a newcomer has been a challenge, especially when it comes to handling file imports and requirements. For my project, I am utilizing getStaticProps for Static Site Generation (SSG) to fetch data from Prismic CMS. Referencing the ...