Trouble with the page not updating after creating or updating a task

Currently, I am developing a project using Next.js along with Drizzle ORM. The main functionality involves creating and updating tasks. However, after submitting the task form, the page navigates back to the homepage, but the newly created/updated task does not appear until I manually refresh the page. Below is the relevant code snippet:

TaskForm.tsx (Client Component):

const onSubmit = async (values) => {
  const response = 
    type === OperationType.Create 
      ? await addTask(values) 
      : await updateTask(defaultValues?.id ?? 0, { ...defaultValues, ...values });

  toast(response.message);

  if (response.success) {
    form.reset();
    router.refresh(); // Attempting to refresh the page
    router.push(redirect ?? "/"); // Redirect to homepage after submission
  }
};

app/page.tsx (Server Component):

export const revalidate = 0; // ISR disabled

export default async function Home() {
  const tasks = await getTasks();
  const completedTasks = tasks.filter(task => task.isCompleted);
  const incompleteTasks = tasks.filter(task => !task.isCompleted);

  return (
    <div className="container">
      <h1>Incomplete Tasks</h1>
      <TodoListTable data={incompleteTasks} />
      <h1>Completed Tasks</h1>
      <CompletedListTable data={completedTasks} />
    </div>
  );
}

actions.ts (Server Actions for Drizzle ORM):

export async function addTask(task) {
  try {
    db.insert(tasks).values(task).run();
    return { success: true, message: "Task created successfully" };
  } catch (error) {
    return { success: false, message: "Error creating task" };
  }
}

Despite successful creation or update of the task, the homepage fails to display the new task unless manually refreshed.

Steps Taken So Far:

  • I attempted to use router.refresh() to reload the page, yet it doesn't seem to reflect the updated data post-task submission.
  • I turned off ISR by setting export const revalidate = 0; in app/page.tsx to ensure fresh data fetch each time.
  • Tried both router.replace() and router.push() without any change in behavior.

What's missing here? How can I guarantee that the homepage consistently shows the latest task list after submission without requiring manual refresh?

Answer №1

The reason for this is related to stored data that is cached. To make changes immediately, we can utilize the revalidatePath function. I encountered a similar issue and successfully resolved it by implementing this function in my own project. For more information, check out the details provided in the documentation on nextJs.

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

What is the best way to change a byte array into an image using JavaScript?

I need assistance converting a byte array to an image using Javascript for frontend display. I have saved an image into a MySQL database as a blob, and it was first converted to a byte array before storage. When retrieving all table values using a JSON ar ...

Retrieving information stored in local storage from a different path using Vuex

Using the config panel route, I am fetching data and setting it to local storage using Vuex and StoreJS: const state = { message: [], // console.log(message); sec: 0, // other state }; const getters = { message: ( ...

Express - Node.js: Setting up a post route on the homepage

When I try to implement form handling on the startpage, an error is displayed by the system. Here is the code using Express: var http = require('http'), express = require('express'), app = express(); app.use(express.bodyParser()); ...

Understanding the Execution of Asynchronous Code

I've been grappling with this problem for a while now, but I just can't seem to find the solution. That's why I'm reaching out for your expertise. Consider the example below: const async = require('async') var counter = 0 v ...

I'm trying to find the location of the server.js file in Node

Currently, I am diving into a book that delves into the integration of nodejs and backbonejs. It covers the foundational aspects that serve as the building blocks for understanding. (...) To kick things off, execute the command 'npm install express& ...

Mongoose makes sure that duplicate rows are not repeated in the database

I'm working with a basic mongoose schema definition below: const mongoose = require('mongoose'); const followSchema = new mongoose.Schema({ follower: { type: mongoose.Schema.Types.ObjectId, ref: 'User', ...

Initiate the process of displaying data on a datetime chart using Highcharts

I am currently developing a yearly chart, but I've encountered a small issue. The chart begins in January, however there is no data available until May. The client specifically wants the chart to only display when there is data available, and unfortu ...

"Customize your search experience with a bootstrap search bar featuring multiple input fields

Currently working on a website using Bootstrap and trying to create a filter bar for the items displayed on the page. I am looking to include one or more input fields (highlighted in red) and one or more dropdowns (highlighted in blue). The width of the ba ...

What is the best way to create a button that will trigger a modal window to display a message?

I am looking to create a button that will open a modal window displaying a message. However, when I tried to add a label and viewed the page, the desired window appeared on top of the rest of the content. But unfortunately, clicking the button did not prod ...

Tracking Time Spent in a Tab using HTML and JavaScript

I have a unique issue that requires a specific solution. Despite my extensive search across the internet, no useful answers were found. This is the snippet of HTML code in question: <form action="/timer.php" method="POST"> <span>Fir ...

Error encountered while attempting to validate JWT

This question has been asked multiple times, but I'm still struggling to find the root cause of the issue. I have already signed some data with a token, but when I attempt to verify it, I receive an error message saying "jwt malformed". Interestingly, ...

What is the process for displaying a PHP array in HTML5 audio and video players?

I am currently working with two PHP arrays. The first array, array "a," contains strings that represent paths for MP3 files on the server. The second array, array "b," contains strings representing paths for MP4 files. For example: $test = 'a.mp3&ap ...

Solving the issue of loading Ember Initializers during the transition to TypeScript

While following the ember quick start tutorial, I attempted to switch from Javascript to Typescript. Converting the .js files to .ts files resulted in an error with the ember-load-initializers import. The application is unable to run until this issue is re ...

What are the steps to styling a component with CSS Emotion?

I am facing an issue with using a theme with TypeScript in this component const buttonDisabled = css` color: ${({ theme }) => theme.color}; `; Is there a way to correctly type this component? Error: No overload matches this call. Overload 1 of 2, & ...

Is there a way to dynamically compute the height of rows in a VariableSizeList based on their index?

Is there a method to dynamically calculate the height of rows in React using the react-window library? Since it's uncertain whether all rows will have the same size, I find myself needing to utilize VariableSizeList. However, I'm wondering if the ...

Preventing default behavior in a JQuery post request

Encountering an issue with jQuery functionality on a mobile device. function send() { $.post("scripts/post.php", { username: $("input[name=username]").val(), password: $("input[name=password]").val() }, function(data) { if ($(".data div" ...

Connecting Mailchimp with WordPress without using a plugin can lead to a Bad Request 400 error when trying to

I'm attempting to connect with Mailchimp using an Ajax request without relying on a plugin, but I keep encountering a 400 bad request error. The code provided below utilizes vanilla JS for Ajax and the function required for integration with Mailchimp. ...

What could be causing the delay in the execution of Redux dispatch?

When I open a file and parse it, the dispatch into redux state takes longer than anticipated. It seems like the dispatch itself is taking several hundred milliseconds more than the reducer. After opening and parsing the file, the following dispatch is mad ...

The type 'Observable<Response | Observable<Response>>' cannot be assigned to the type 'Observable<Response>'

My service features a basic structure: import { Injectable } from '@angular/core'; import { Http, Response } from '@angular/http'; import 'rxjs/add/observable/throw'; import 'rxjs/add/operator/catch'; import ' ...

Creating various containers in React JS for different components

I am faced with the task of rendering multiple DOM elements from my JavaScript code. Imagine I have div elements like this: <div id="div1"><div> //Some Html tags <div id="div2"><div> //Some Html tags <div id="div3" ...