Is there a way to get UseMemo to recognize the value from zod validation?

Having trouble resolving an error in my code. I used zod for data validation and tried using the useMemo function, but when I input the value that has been validated by zod, an error occurs as shown in the image. I even tried adding an index to the value, but it didn't work. Any suggestions on how to fix this?

const apiScheme = z.tuple([
      z.object({
         total_work_hours: z.number().nullable(),
         normal_hours: z.number().nullable(),
         overtime: z.number(),
         public_holiday_hours: z.number(),
         total_work_days: z.number(),
         total_medical_leave: z.number(),
         total_emergency_leave: z.number(),
         total_public_holiday: z.number(),
      }),
      z.array(
         z.object({
            date: z.string(),
            attendance: z.array(
               z.object({
                  outlet_name: z.string().nullable(),
                  clock_in_type: z.string().nullable(),
                  clock_in: z.number().nullable(),
                  clock_out: z.number().nullable(),
                  work_hour: z.number().nullable(),
               }),
            
            ),
         }),
      ),
   ]);
   // console.log(apiScheme);

   const data1 = useMemo(() => {
      if (responseAttendanceData) {
         const parseData = apiScheme.parse(responseAttendanceData);
         if (parseData) {
           return parseData.map((value)=>{
             return{
                total_work_hours: value.total_work_hours,
                normal_hours: z.number().nullable(),
                overtime: z.number(),
                public_holiday_hours: z.number(),
                total_work_days: z.number(),
                total_medical_leave: z.number(),
                total_emergency_leave: z.number(),
                total_public_holiday: z.number(),
                
             }
           })
         }
      }
      return null;
   }, [responseAttendanceData]);

Answer №1

After assessing your concerns, it appears that UseMemo is incompatible with async functions, rendering it unsuitable for handling your data. Instead, consider utilizing UseEffect and UseState to effectively execute your concept without encountering this roadblock. I trust that implementing these alternatives will assist in overcoming the mentioned issue. Thank you for considering my suggestion.

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

Tips for extracting specific JSON response data from an array in TypeScript

I have an array named ReservationResponse, which represents a successful response retrieved from an API call. The code snippet below demonstrates how it is fetched: const ReservationResponse = await this.service.getReservation(this.username.value); The st ...

JavaScript: How to clear an array after using a forEach loop

I'm currently developing a project for managing a store using NestJS and Mongoose. Within my code, I am trying to update certain items in the database and store these updated items in an array for later use. const updatedItems: Item[] = []; purchase ...

Ways to verify a single field within a Zod schema individually rather than the entire schema

I am currently working on a form that consists of multiple inputs, including 'hours' and 'price'. The technology stack I am using is NextJS along with server-side actions. When a user clicks the submit button, here's what happens: ...

Ways to receive a reply from EventEmitter

From the child component, I made a call to a certain method. Here is the code in the child component: @Output() parentEvent = new EventEmitter<any>(); click1() { //calling the specified method from the child this.parentEvent.emit(myObj1); ...

Selecting the checkbox to populate the input field

In my application, there is an input field that can be filled either by searching for an item or by clicking on a checkbox. When the user clicks on the checkbox, the input should be automatically filled with the default value valueText. How can I detect ...

The resolution of Angular 8 resolver remains unresolved

I tried using console.log in both the constructor and ngOnInit() of Resolver but for some reason, they are not being logged. resolve:{serverResolver:ServerResolverDynamicDataService}}, console.log("ServerResolverDynamicDataService constructor"); console ...

How can conditional types be implemented with React Select?

I am working on enhancing a wrapper for React-select by adding the capability to select multiple options My onChange prop is defined as: onChange: ( newValue: SingleValue<Option>, actionMeta: ActionMeta<Option>, ) => void Howev ...

Restrict the scope of 'unknown' to an object containing only a string-field without resorting to 'any'

Currently, I am working on validating the data that is being received by my application. To illustrate, consider the following scenario: function extractField(data: unknown): string { if (typeof data !== 'object') { throw new Error(& ...

What is the most effective way to send messages from Typescript to C#?

Could someone provide guidance on how to properly send a message from Typescript to C#? I have been attempting to receive the message in C# using WebView_WebMessageReceived with the code snippet below: private void WebView_WebMessageReceived(object sender, ...

Why does the CSHTML button containing a JavaScript onclick function only function intermittently?

I've implemented a download button on a webpage that dynamically assigns an ID based on the number of questions posted. Below is the code for the button: <input data-bind="attr: { id: $index() }" type="button" value="Downlo ...

Retrieve unique elements from an array obtained from a web API using angular brackets

I've developed a web application using .NET Core 3.1 that interacts with a JSON API, returning data in the format shown below: [ { "partner": "Santander", "tradeDate": "2020-05-23T10:03:12", "isin": "DOL110", "type ...

Transform this React-Redux function component into a class component

After following the guide provided on https://github.com/Microsoft/TypeScript-React-Starter to set up my project, I encountered an example with a react component as a function. This is the current code snippet: export interface Props { name: string; ...

Interface for exporting TypeScript models

I am a beginner in TypeScript and have a question regarding the code where the (position) is referencing another TypeScript model. Both models are located in the 'model' folder: export interface Group { name: string; opportunities: Opportu ...

Do I still need to use @types/core-js for TypeScript typings in a Node.js application?

I manage multiple Node.js projects that focus on backend development and utilize a straightforward TypeScript setup. Prior to March 2018, my package.json file included the following: "devDependencies": { "@types/core-js": "^0.9.46", "@types/nod ...

"Encountering a build failure in Next.js when using getStaticProps because a parameter is returning undefined

An unusual error has recently surfaced, causing our builds to fail, Located within the pages directory is a post/[id].tsx file that utilizes getStaticProps and getStaticPaths -- props export const getStaticProps: GetStaticProps = async ({ params }) => ...

The TypeScript package encountered an unexpected token export

I have integrated a module from a private git repository. Package.json: "my-module": "git+https://username:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cebeb98eaca7baacbbada5abbae0a1bca9">[email protected]</a> ...

Enable the use of unfamiliar techniques on object

I am facing a challenge with an object that contains multiple method names which are not known at compile time. The signature of these methods always remains the same, but I am unsure about how to handle this scenario. I attempted to utilize an index type ...

What is the best way to trigger a mat-menu to open with just one click, while also automatically closing any other open menus at

I've encountered an issue where if there are multiple menus in the header, opening a menu for the first time works fine. However, if a menu is already open and I try to open another one, it doesn't work as expected. It closes the previously opene ...

Refine the search outcomes by specifying a group criteria

I have a scenario where I need to filter out service users from the search list if they are already part of a group in another table. There are two tables that come into play - 'group-user' which contains groupId and serviceUserId, and 'gro ...

Refining Generic Types in TypeScript

Why does the generic type not narrow after the type guard in typescript v4.4.4? Is there a way to resolve this issue? type Data = X | Y | Z type G<T extends Data> = { type: 'x' | 'y' data: T } type X = { name: string } type ...