Having issues with rendering in Next JS app following deletion function

After successful testing on my local environment, I encountered strange behavior when the code was pushed to the main branch and deployed on Vercel with a Postgres DB. While creating projects and skills worked without any issues, deleting items resulted in inconsistencies. Despite being deleted from the database, the site failed to update properly, causing additional projects to disappear even though they still existed in the DB.

skill-view-card.tsx

'use client'

import { deleteSkill, createProject, deleteProject } from '@/app/lib/actions';
import { Button } from '@nextui-org/react';
import { TrashIcon } from '@heroicons/react/20/solid';


export default function SkillViewCard({ skills, projects }: { skills: string; projects: string }) { // after performing certain actions, outdated data is fetched
  const skillsParsed = JSON.parse(skills); // refetching required
  const projectsParsed = JSON.parse(projects);

  function toTitleCase(str: string) {
    return str.replace(/\w\S*/g, (text: string) => text.charAt(0).toUpperCase() + text.substring(1).toLowerCase());
  }

  return (
    <div className="p-8 border w-full h-full shadow-lg rounded-md bg-white">
      <div className="columns-2">
        <div className="text-left text-xl font-bold">
          {toTitleCase(skillsParsed?.description) || 'No description available'}
        </div>
        <Button onClick={() => { deleteSkill(skillsParsed.id);}}>
          <TrashIcon className="h-4 w-4 content-right" />
        </Button>
      </div>
      <div className="columns-1">
        <fieldset>
          {projectsParsed && projectsParsed.length > 0 ? (
            projectsParsed
              .filter((project: { skill_id: string }) => project.skill_id === skillsParsed?.id)
              .map((project: { title: string, id: number }) => (
                <div key={project.id}>
                  <div>{project.title}</div>
                  <Button onClick={() => { deleteProject(project.id);}}>
                    <p>Delete</p>
                  </Button>
                </div>
              ))
          ) : (
            <p className="text-gray-500">No projects available</p>
          )}
        </fieldset>
      </div>
      <div className="columns-2"></div>
      <input
                type="text"
                placeholder="Enter project title"
                className="border rounded-md p-2 w-half"
                onKeyDown={(e) => {
                    if (e.key === 'Enter') {
                        e.preventDefault();
                        const formData = new FormData();
                        formData.append('title', e.currentTarget.value);
                        formData.append('skill_id', skillsParsed.id);
                        createProject(formData);
                        e.currentTarget.value = '';
                    }
                }}
            />    
        </div>
  );
}

@/app/lib/actions

'use server';
import { sql } from '@vercel/postgres';
import { redirect } from 'next/navigation';

export async function createSkill(formData: FormData) {
    const skillDescription = formData.get('skill') as string | null;

    await sql`
    INSERT INTO skills (description)
    VALUES (${skillDescription || ''})
  `;

  redirect('/test-page?refetch=true'); // data needs to be refetched
}

export async function deleteSkill(id: number) {
    await sql`
    DELETE FROM skills WHERE id = ${id}
    `;

    redirect('/test-page?refetch=true');
}

export async function createProject(formData: FormData) {
    const projectTitle = formData.get('title') as string | null;
    const skillId = formData.get('skill_id') ? parseInt(formData.get('skill_id') as string, 10) : null;

    await sql`
    INSERT INTO projects (title, skill_id)
    VALUES (${projectTitle || ''}, ${skillId || ''})
  `;

  redirect('/test-page?refetch=true');
}

export async function deleteProject(id: number) {
    await sql`
    DELETE FROM projects WHERE id = ${id}
  `;
  redirect('/test-page?refetch=true');
}

Answer №1

If you're experiencing any caching issues, I suggest using the revalidatePath function. Learn more about revalidatePath here. It's crucial to focus on server-side operations when implementing this, so make sure to use it in conjunction with "use server".

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

Trouble with Scroll Snap and Navbar Toggle Malfunctioning on Browser Resize

I've run into a problem with scroll snap on my website. Every time the screen size changes, like when the mobile browser's navbar is opened or closed, the scroll snap behavior goes haywire. Even after returning to the top of the page, the snap fe ...

"Polymer 1.x vs React: A comparison of two powerful

I am currently facing a challenge in integrating web components built with Polymer v1 into our app that is developed using the latest version of React (16.3.2 as of now). The integration works smoothly on major browsers like Chrome, Edge, and Firefox. How ...

Transferring a method through two layers of hierarchy

I'm currently working on a fun little game project, but I've hit a roadblock when it comes to passing a particular method down to its grandchildren components. Despite finding similar discussions on this topic, none seem to address my specific qu ...

How can you retrieve the length of an array in Mongoose/Node.js and utilize it as a counter?

After making changes to my algorithm, I have a new question that differs from the problem discussed here (a solution has been provided in that thread). What is this about ? const mongoose = require('mongoose'); const sauceSchema = mongoose.Schema ...

Transforming a DOM JavaScript Object into a React element

Currently, I am utilizing a library that returns a Dom object of an HTML element. My goal is to set this dom object to the state in reactjs and then render it to the UI like so: this.setState({ video: videoElement }) render () { return ( < ...

Tips for organizing an object according to specific attributes

Within my table, I have implemented a feature that allows the display of only selected columns at a time. To achieve this, I store the chosen columns (table headings) in an array called selectedTableHeaders. The next step is to filter out a new array bas ...

What is the proper way to utilize JQuery and Ajax to communicate with a global function in writing?

My goal is to retrieve data from an AJAX request and store it in a global variable. Despite trying to make the call synchronous, I am encountering issues where the value of the global variable becomes undefined outside of the Ajax request. I have attempt ...

What could be causing errors when trying to assign keys in React?

Struggling with an error message while working on the ReactJS demo for ASP.NET Core. The warning says: Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of CommentList. See url for more information. ...

Is there a way to retrieve the precise floating-point width of an element?

When attempting to determine the precise width of a table cell, I encountered some discrepancies. While IE9's developer toolbar indicated a width of 203.68px in the Layout tab, using element.clientWidth and other methods yielded a rounded integer valu ...

Using React to dynamically change the page based on button clicks

Currently, I am facing a challenge with my react application development. This is my first time working on a react project and I am encountering some issues. In one of the functional components, I am calling and displaying another functional component twic ...

"Exploring the world: a guide to using map and

I am having trouble with the area tag in my HTML code. <!--images--> <img align="center" src="C:\Users\RS\Pictures\fotoshop\ananimous.png" alt="ananimouse" width=& ...

A guide to writing a script to access and return a specific element stored in an array within an object's property

I have created this specific function function extractSingleValue<T, TElem, K extends keyof T>(obj: T, name: K): TElem { const source = obj[name]; if (source.length !== 1) { throw Error(`There should be exactly one ${name} associated`); } ...

Changing the value causes the input to malfunction (Node.js)

Looking to add content to the text input field on the website . When manually entering characters, all elements load automatically. However, using this code: document.getElementsByClassName("navbtn")[0].value += "d" does not generate new results and causes ...

Unpacking Reddit's JSON data in a Node environment proves challenging as the Javascript parser seems to have a distaste for

Hey there, I hope everything is going well! I've been working on a project that involves scanning the JSON data from reddit.com/r/pics. My goal is to extract a random image and display it on a webpage. The issue I'm facing is that Reddit's ...

What is the process to set up a WebSocket on Tornado for a production server rather than on a local machine?

Recently, I've delved into the world of WebSockets but have only experimented with them in a localhost environment while developing locally. Following this informative tutorial on real-time data visualization: https://medium.com/@benjaminmbrown/real-t ...

Utilizing Node.js, Socket.io, and P5.js to generate an interactive live video feed

I am attempting to set up a basic video stream on my local network. However, the current code is triggering the following error message: Uncaught TypeError: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The provided val ...

Is there a way to load an image onto the ngx-image-cropper without triggering the imageChangedEvent event?

My latest project involved creating a custom cropper using ngx-image-cropper, which allows for cropping and rotating images. For the sprint demo, I needed the images to be displayed as soon as the application loads without having to trigger the fileChangeE ...

Testing API route handlers function in Next.js with Jest

Here is a health check function that I am working with: export default function handler(req, res) { res.status(200).json({ message: "Hello from Next.js!" }); } Alongside this function, there is a test in place: import handler from "./heal ...

Firestore is failing to accept incoming data when the setDoc method is employed

I am encountering an issue with my app's connectivity to the Firestore database when attempting to utilize setDoc. The database is successfully operational for next-auth, creating records as intended. However, the problem arises when trying to enable ...

Instead of the typical Three.js pointer lock first person controls, how about experimenting with orbit

I'm struggling to understand why my controls are causing the camera to orbit around a fixed point instead of behaving like a first-person shooter game. After comparing my code to an example in the three.js documentation, I am aiming to replicate the ...