Issue arising from passing an object through a component in a Next.js application during build time when the object is retrieved from a database

Can anyone provide assistance with solving this issue? I have an object called "diary" coming from a database, which is passed to a component where a useState hook is expecting that object. During build time, the following error is occurring.

An error is showing in the terminal during build time (https://i.sstatic.net/JIlnQ2C9.png)

import { db } from "@/db";
import DiaryEditForm from "@/components/diary-edit-form";
interface DiaryEditPageProps {
    params: {
        id: string;
    };
}
export default async function DiaryEditPage(props: DiaryEditPageProps) {
        const id = parseInt(props.params.id);
        const diary = await db.diary.findFirst({
            where: { id },
            });
        return (
        <div>
        <DiaryEditForm diary={diary} />
        </div>
    );
}
"use client";

import { Diary } from "@prisma/client";
import { useState } from "react";
import * as actions from "@/actions";

interface DiaryEditFormProps {
  diary: Diary;
}
export default function DiaryEditForm({ diary }: DiaryEditFormProps) {
  const [content, setContent] = useState(diary);
  const handleEditorChange = (event: {
    target: { name: string; value: string };
  }) => {
    const { name, value } = event.target;
    setContent((prevContent) => ({
      ...prevContent,
      [name]: value,
    }));
  };
  const editDiaryAction = actions.editDiary.bind(
    null,
    diary.id,
    content.title,
    content.description
  );
  return (
    <form action={editDiaryAction} className="space-y-4">
      <h1 className="text-center font-semibold">Edit your Diary</h1>
      <div>
        <label
          htmlFor="title"
          className="block text-gray-700 font-medium mb-2 leading-tight"
        >
          Title
        </label>
        <input
          type="text"
          name="title"
          id="title"
          value={content.title}
          onChange={handleEditorChange}
          className="w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:border-gray-500"
        />
      </div>
      <div>
        <label
          htmlFor="description"
          className="block text-gray-700 font-medium mb-2 leading-tight"
        >
          Description
        </label>
        <textarea
          name="description"
          id="description"
          value={content.description}
          onChange={handleEditorChange}
          className="min-h-32 w-full px-3 py-2 border border-gray-300 rounded focus:outline-none focus:border-gray-500"
        ></textarea>
      </div>

      <button
        type="submit"
        className="bg-gray-600 text-white px-4 py-2 rounded"
      >
        Save
      </button>
    </form>
  );
}

Any suggestions on how to resolve this type error?

Answer №1

The Diary application interface rejects any instances of a null value. As a result, when the API call is made to retrieve data, it initially returns null causing a type error. To resolve this issue, update the following code snippet to allow for nullable values:

interface UpdatedDiaryEditFormProps {
    diary: Diary |null;
}

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 method for retrieving GET parameters in an Angular2 application?

Is there a way in Angular2 to retrieve GET parameters and store them locally similar to how sessions are handled in PHP? GET Params URL I need to obtain the access_token before navigating to the Dashboard component, which makes secure REST Webservice cal ...

"Fetching and Utilizing the Output Parameter from an API in Angular4: A Step-by-Step Guide

Working on a post method in an Angular 4 web app, I am able to save data to the database successfully. However, I am facing an issue where an ID (return value) is passed from the DB to the API for Angular as another function parameter. How can I retrieve t ...

Is there a solution for the error "Unable to persist the session" in a Next.js application that utilizes Supabase, Zustand, and Clerk.dev for authentication?

I have successfully set up a Next.js application with Clerk.dev for authentication and Supabase for data storage. I'm also leveraging Zustand for state management. However, an error is plaguing me, stating that there's "No storage option exists t ...

Redirect URL problem in the PayPal login function

After setting up the URL as http://127.0.0.1:3000/link-paypal on my profile and dashboard, I encountered an issue when trying with localhost. The system prompted me to try again, for reasons unknown, hence now switching to 127... In addition, I replaced t ...

The SWA command line interface emulator experiences a crash when SSL is enabled on the NextJS development server

While attempting to run the NextJS development server with SWA emulator, I encountered a crash after enabling SSL and making the first request. Strangely, if I do a static export of the NextJS site and use that folder with the emulator, everything works sm ...

Typescript Support in Goland IDE for HTML Documents

I'm currently utilizing Go for my programming tasks, and I prefer the Goland IDE developed by Jetbrains. Is there a way for me to incorporate typescript into my .html template files that contain a mix of HTML, CSS, and JS? Your assistance is much ap ...

Is it necessary for me to individually download every x.d.ts file for my application?

Do I need to include the following line for type checking when using fs.readFile in TypeScript? /// <reference path="node.d.ts" /> Is it considered 'best practice' to download and maintain the most recent version of node.d.ts file in my ...

The object 'key' is not a valid property of the type 'Event'

Recently, I decided to delve into Tauri using vanilla Typescript code. Oddly enough, when working in vscode, it flagged event.key and foo_input.value as not properties of Event. However, when running the Tauri application, everything worked perfectly fine ...

Error: Property 'mytest' is undefined and cannot be read

While working with Swagger API, I encountered an error message when calling the endpoint stating "Cannot read property 'mytest' of undefined" class UserData { private mytest(req:any, res:any, next:any){ return res.json('test32423423&a ...

The Vue router fails to load when using create-vue@3

I've been experimenting with the Vue Router, but it's not giving me the expected outcome. While following the tutorial on https://router.vuejs.org/guide/, I found that if I use the CDN and place it in a standalone HTML file, it works fine. Howev ...

Creating a dynamic type class in TypeScript that can inherit characteristics from another class

Can a wrapper class be designed to dynamically inherit the properties of another class or interface? For instance... interface Person { readonly firstName: string; readonly lastName: string; readonly birthday?: Date } class Wrapper<T> { ...

Guide on making requests in SSR component of Strapi + Next.js App Router using GraphQL and Apollo

I've successfully set up a Next.js project with Strapi and I'm using GraphQL + Apollo for querying. However, when attempting to query using Apollo in an SSR component, I encountered the following error: - Error: Attempted to call query() from t ...

Why is Typescript converting my keyof type to a never type and what steps can I take to resolve this issue?

Apologies if this question is repetitive, as I am new to TypeScript and struggling to identify related issues due to the complexity of some questions. The issue I'm facing involves TS coercing a type to never, which is confusing me. Here's the sc ...

Angular Typescript error: Trying to assign a value to 'someProperty' property of an undefined object

Within my Article class, I have a property called Image which is structured like this: export class Article { public image:Image; public images: Image[]; } If I decide to comment out this.article.image = new Image(); in the following way: constru ...

TS2367: Given any input, this condition will consistently evaluate to 'false'

I'm struggling to understand why the compiler is not including null as a possible type for arg, or perhaps I am misinterpreting the error message. static vetStringNullable(arg:any): string|null { if (typeof arg === 'string') { ...

The Next.js client-side JavaScript application experiences unforeseen disruptions without generating any console errors

My server is responsible for constructing HTML from a JSON response: { content: "<div id=\"_next\">...</div>...<script src=\"...\"></script>" } This is how my Node server handles the data: const output = "&l ...

next-redux-wrapper is being invoked repeatedly and experiencing multiple calls to HYDRATE

I'm embarking on a new Next.js project, transitioning from a standard React app to a Next.js application. Our plan is to utilize Redux Toolkit for global state management and incorporate server-side rendering. During this process, we discovered the ne ...

What is the best approach to organize data from an observable based on a nested key?

I'm currently developing a new application and struggling with grouping data. The data is being pulled from an observable, and I need to group objects by their status and push them into an array. I attempted to use the groupBy() method, but unfortunat ...

Does the React memo function modify the component's prop type?

I've come across a strange issue where defining two components causes compilation errors when written separately but not when written in the same file. test3.tsx import React from "react"; type ValueType = number[] | string[] | number | st ...

How to extract a string value from an observable array in Angular2 NativeScript?

I inserted JSON data into an observable array. My goal is to extract only the address from ShowData, specifically as a string value based on its position. ShowData.ts: class ShowData{ constructor(public id:number, public name:string, public address:s ...