What could be causing the error message "Property 'x' does not exist on type '{ error: string; }'.ts(2339)" to appear when attempting to prefill data from the database?

Recently, I encountered an issue while trying to fetch a single data from the database and create a component for editing user input. TypeScript threw a warning at me that read:

Property 'title' does not exist on type '{ error: string; }'.ts(2339)

This is how my zod schema looks like:

const formSchemaData = z.object({
    title: z.string().min(2, {
      message: "title must be at least 2 characters.",
    }),
    email: z.string().min(2, {
      message: "email must be at least 2 characters.",
    }).email(),

    //other code   
  })

export type Events = z.infer<typeof formSchemaData>
 const { data, error, isFetching } = useQuery({
    queryKey: ["eventId", eventId],
    queryFn: async () => await getDataById(eventId),
  });

  const form = useForm<Events>({
    resolver: zodResolver(formSchemaData),    
  });

return (
<Form {...form}>
        <form>
        <FormField
          control={form.control}
          name="title"
          defaultValue={data ? data.title : ''} 
          render={({ field }) => (
            <FormItem>
              <FormLabel>Title</FormLabel>
              <FormControl>
                <Input 
                  placeholder="title"
                  {...field} />
              </FormControl>
              <FormDescription>
                This is your public display name.
              </FormDescription>
              <FormMessage />
            </FormItem>
          )}
        />
)

I follow this process to fetch data from the database:

export async function getDataById(id: any){
  try {
    const data = await db.appointmentSchedule.findUnique({
      where: {
        id:id
      }
    })

    return data
  } catch (error) {
    return {error: "Something went wrong"}
  }
}

If you want to view additional details about types, please check this link.

Unfortunately, I can't share the entire code due to a warning received from Stack Overflow.

Answer №1

Expanding on the input from Nicholas Tower, the reason behind this caution becomes more apparent when you explicitly define the return type of getDataById:

export async function getDataById(id: any): Promise<
  | { title: any; email: string }
  | { error: string }
> {
  // ...
}

Given that the return type could be either { title: any; email: string } or { error: string }, the compiler cannot ensure the presence of the title field while assigning defaultValue:

defaultValue={data ? data.title : ''}

To address this issue, it is crucial to handle scenarios where an error occurs:

const { data, error, isFetching } = useQuery({
  queryKey: ["eventId", eventId],
  queryFn: async () => await getDataById(eventId),
});

const form = useForm<Events>({
  resolver: zodResolver(formSchemaData),    
});

if ("error" in data) {
  // This is just a demonstration; you should present a suitable UI to the user
  return <>{data.error}</>;
}

// If `"error" in data` returns false, then data
// must conform to the structure of `{ title: any; email: string }`

return (
  <Form {...form}>
    <form>
      <FormField
        control={form.control}
        name="title"
        defaultValue={data ? data.title : ''} // No need to worry about warnings now, as data.title is guaranteed to be defined
        {/* ... */}
      />
    </form>
  </Form>
)

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

The concept of type literals in Typescript provides a powerful tool for achieving function

In TypeScript, I am aiming to create an overloaded function with named parameters. Despite the code running correctly, I encounter warnings about `init.index` potentially not existing in one of the function signatures. The purpose of overloading is to off ...

Utilize IDE's capabilities to recommend mutations and actions during the process of committing or dispatching

In my current Vue 3 Typescript project, I am utilizing Vuex. The code snippet below showcases how I have implemented it: import { createStore, useStore as baseUseStore, Store } from 'vuex'; import { InjectionKey } from 'vue'; export i ...

Is there a way to incorporate multiple plan tiers on Stripe's platform?

//api/stripe import { auth, currentUser } from "@clerk/nextjs/server"; import { NextResponse } from "next/server"; import { prismadb } from "@/lib/prismadb"; import { stripe } from "@/lib/stripe"; import { absoluteUr ...

Tips for properly displaying mathematical equations using MathJax in Angular6

I have successfully loaded mathematical equations using the code below. Now, I aim to integrate it within an Angular environment. How can I convert this code for Angular compatibility? <script src='https://cdnjs.cloudflare.com/ajax/libs/mathjax/2. ...

Troubleshooting Type Error in React with Typescript: Finding Solutions for HTMLButtonElement Issue

Hey there! I recently created a TodoList Sample using React, Redux, Typescript, and SCSS. However, I encountered an issue with Typescript error which states the following: Error Status: Type '(event: { target: HTMLButtonElement; }) => void' ...

Troubleshooting: Video.js not responding to m3u8 video format in the most recent

In my next.js project, I am incorporating the video.js npm library to handle videos in m3u8 format. The video.js component below is responsible for displaying these videos. While testing on my localhost, I encountered an issue where the video sometimes lo ...

How can Vue be used to dynamically change the input type on focus?

What Vue method do you recommend for changing an input element's type on focus? e.g. onfocus="this.type = 'date'" I am specifically looking to switch the input type from text to date in order to utilize the placeholder property. ...

Encountered a Webpack error when trying to load the DomUtils module following the

I'm currently working on a project that involves TypeScript and React 0.14. I've set up my test environment using karma/mocha/chai, and it seems to be functioning well. However, when I try to import and use a function from enzyme, I encounter an ...

What is the best way to implement a mixin reducer for functional typing?

Currently, I am in the process of learning typescript and facing challenges in understanding how to correctly type a reducer function that reduces functional mixins. Let's consider two functional mixins: type FooComposable = { foo: string; }; const ...

Attempting to set a JavaScript variable as the placeholder value without any user interaction in Next.js

In my form, I have four inputs: token_name, token_expire_date, token_issue_date, and token_value. The first two require user input, while the second two are predetermined values (token_issue_date and token_value). Despite being predetermined, I need all th ...

What steps should I take to create a React component in Typescript that mimics the functionality of a traditional "if" statement?

I created a basic <If /> function component with React: import React, { ReactElement } from "react"; interface Props { condition: boolean; comment?: any; } export function If(props: React.PropsWithChildren<Props>): ReactElement | nul ...

Troubleshooting the "Callback URL mismatch" error in your NextJs Auth0 application

I am currently implementing authentication in my NextJS App using the Auth0 NextJs SDK. I have been following a helpful tutorial on it which you can find here. Everything is running smoothly on my local machine at the moment. Here is the configuration for ...

During production in Next.js, headers are stripped from middleware

Something peculiar is happening with my project on next js 12.3. I am using middleware to add a canonical link to headers. Strangely, everything works perfectly locally and the required headers are added as expected. However, when deployed to production, t ...

Ensuring that passwords match during validation

My goal is to compare the values of the password and confirm password inputs. Even when I enter the same value in both fields, an error saying 'Password does not match' still appears. Component validate(): boolean { this.appErrors = []; ...

Steps to Transform String Array into Prisma Query Select Statement

I have a requirement to dynamically select Prisma columns based on client input: ['id', 'createdAt', 'updatedAt', 'Order.id', 'Order.Item.id', 'Order.Item.desc'] The desired format for selection ...

Exploring Immediately Invoked Function Expressions in TypeScript

I came across an interesting article on self-invoking functions in JavaScript by Minko Gechev. This article teaches us how to create a JavaScript function that calls itself immediately after being initialized. I am curious about how we can achieve this in ...

The object holds a value

How can I successfully put an object into a value attribute, for example: <option value={valueSort}>// valueSort = {name: 'ASC'}, to sort by name in my project? Currently, the result shows as [object Object] and I'm unsure of what that ...

Staying patient while the array loads data from Firebase so that methods can be called efficiently

As an Angular newbie, I am working on a project that involves accessing data from Firebase using an Angular service. My goal is to retrieve this data, store it in an array, and then perform some operations on that array. However, due to my limited experien ...

When transitioning to generics, the narrowing of types in TypeScript is sometimes lost

I am intrigued by this scenario where Test1 fails while Test2 succeeds. I wonder if there is a way to have Test1 pass without altering the generic signature: enum TableType { Shipment = "Shipment", Batch = "Batch", } type Test& ...

"Exploring the world of Angular, promises, and effective caching strategies in

In my Angular application, there is a service responsible for loading items from the server. When an item is selected in a view, the corresponding item should be retrieved from the list and displayed in detail. The issue arises when I reload the page – ...