관리 메뉴

Silver Library (Archived)

useForm, data interaction, and controller in nest.js 본문

카테고리 없음

useForm, data interaction, and controller in nest.js

Chesed Kim 2023. 3. 1. 21:11
반응형



Q1.

 

In reactjs, there is hook calls react-datepicker. I set a query path to call date data from backend server with axios either get and post, and there are two input, these are in the <form> tag. This form tag includes something like this:

 

<form onSubmit={handleSubmit()}>

    </form>

 

In this form tag, there are two loaded react-datepicker as <DatePicker>. Suppose, first DatePicker is start date, and second DatePicker is end date. Which means, second DatePicker must follow or aware about the changes (selected value) of first DatePicker. I reckon setValue is the thing I can implement to its example.

 

Can you show me how it looks like then? And explain me so I can understand how the logic should be.

 

A.

Yes, you can use setValue method from react-hook-form to achieve this goal. Here is how you can implement it:

  1. First, you need to import useForm hook from react-hook-form:

import { useForm } from 'react-hook-form';

 

  1. Initialize useForm hook in your component and create two fields for start date and end date:

const { register, setValue, handleSubmit, watch } = useForm();

const startDate = watch('startDate');

const endDate = watch('endDate');

 

  1. Then, you need to register both DatePicker fields with register method of react-hook-form. Make sure to set name attribute of each DatePicker to 'startDate' and 'endDate' respectively.

<DatePicker

  name="startDate"

  selected={startDate}

  onChange={(date) => setValue('startDate', date)}

  // Other props...

/>

 

<DatePicker

  name="endDate"

  selected={endDate}

  minDate={startDate}

  onChange={(date) => setValue('endDate', date)}

  // Other props...

/>

 

Here, we are using the setValue method to set the value of the startDate and endDate fields in the form data.

  1. Now, we need to add validation rules to make sure that the end date is always greater than or equal to the start date.

const { register, setValue, handleSubmit, watch, formState: { errors } } = useForm({

  criteriaMode: "all"

});

const startDate = watch('startDate');

const endDate = watch('endDate');

 

register('startDate', { required: true });

register('endDate', {

  required: true,

  validate: (value) => value >= startDate || "End date must be greater than or equal to start date"

});

 

  1. Finally, we need to handle form submission using handleSubmit method and send the form data to the server using Axios:

const onSubmit = (data) => {

  axios.post('/api/submit', data)

    .then((response) => {

      // Handle success response...

    })

    .catch((error) => {

      // Handle error response...

    });

};

 

return (

  <form onSubmit={handleSubmit(onSubmit)}>

    // Render DatePicker fields...

    <button type="submit">Submit</button>

  </form>

);

 

Here, we are passing the onSubmit function to the handleSubmit method, which will be called when the form is submitted. The onSubmit function will receive the form data as its argument, which we can send to the server using Axios.

I hope this helps you understand how to use setValue in react-hook-form to make one DatePicker field dependent on another DatePicker field. Let me know if you have any further questions!

 

Q2. 

In nest.js, if I don't set something (I guess that was controller), when I make post or get request with axios, I will get the error like 'x property should not exist'. When this error may occur, I mean what setting woud be missed if I see such error message in console?

 

A.

The error message you're seeing ("x property should not exist") is a TypeScript error message, indicating that you're trying to access a property that doesn't exist on a particular object.

This error can occur in a Nest.js application if you're trying to use a property that doesn't exist on a controller, service, or other component. For example, if you're trying to call a method on a controller that doesn't exist, you'll see this error message.

To fix this error, you should check your code to see where the property is being accessed, and make sure that the property exists on the object you're trying to access it on. You may also need to make sure that any interfaces or classes that define the object have the correct properties and types.

Additionally, it's possible that you're missing an import for a particular module or class that defines the property you're trying to access. In this case, you'll need to make sure that you've imported all the necessary modules and classes in your code.

Overall, this error message can occur for a variety of reasons, but it generally indicates that there's an issue with your code that needs to be addressed.

 

Q continue

Hang on, I saw the thing I input as query path and its object was on the list when I did console.log, but  it just showed up 'entryEndAt property should not exist'. Probably this is due to not setting up 'something' on my backend side, nest.js. Take note, it looked something like this (see the code I share).

 

export class SomethingDto {

@NotEquals(null)

@ValidateIf((object, value) => value !== undefined)

@IsUrl()

url: string;

 

@NotEquals(null)

@ValidateIf((object, value) => value !== undefined)

@Min(1)

@IsNumber()

missionIdx: number;

 

@NotEquals(null)

@ValidateIf((object, value) => value !== undefined)

@Min(1)

@IsNumber()

ownerIdx: number;

 

@NotEquals(null)

@ValidateIf((object, value) => value !== undefined)

@Min(1)

@IsNumber()

mediaIdx: number;

 

@IsOptional()

description: string;

}

 

A.

Based on the code you provided, it looks like you have a Nest.js DTO (Data Transfer Object) called SomethingDto, which is used to define the shape of the data that's expected to be passed to an API endpoint when creating new "entry" resources.

The DTO has several validation decorators, such as @IsUrl(), @IsNumber(), @Min(1), and @NotEquals(null), which are used to ensure that the incoming data meets certain requirements. For example, the @IsUrl() decorator ensures that the url property is a valid URL string, while the @IsNumber() and @Min(1) decorators ensure that the missionIdx, ownerIdx, and mediaIdx properties are positive numbers.

However, without seeing the rest of your code it's difficult to say exactly where the error is coming from. If you're seeing an error message that says "entryEndAt property should not exist", it's possible that there's a typo in your code somewhere that's causing the property to be accessed incorrectly. Alternatively, it's possible that there's a mismatch between the DTO and the data being passed to the endpoint.

Regarding your developer's advice, it's difficult to say exactly what they meant without more context. However, in general, Nest.js controllers are responsible for handling incoming requests and returning responses. They typically define methods that map to different HTTP verbs (e.g. GET, POST, PUT, etc.) and are decorated with route paths that define the URL for the endpoint. For example:

@Controller('entries')

export class EntriesController {

  constructor(private readonly entriesService: EntriesService) {}

 

  @Post()

  create(@Body() createEntryDto: CreateEntryDto) {

    return this.entriesService.create(createEntryDto);

  }

 

  // other methods here...

}

 

In this example, the @Controller('entries') decorator defines a base route path for all methods in the controller (e.g. /entries). The @Post() decorator maps the create() method to the POST /entries endpoint, and the @Body() decorator tells Nest.js to parse the request body and inject it as the createEntryDto parameter.

If you're seeing errors related to a missing controller or a missing route, it's possible that you haven't defined the controller or route correctly, or that you're trying to access a route that doesn't exist. In general, you should ensure that your routes and controllers are defined correctly, and that your API endpoints are returning the expected responses.

 

React hook form:

https://mjn5027.tistory.com/40