I'm using react-hook-form. I'm trying implemnet shopping cart with this library, but getting struggle with get number value. the input tag which name="count" always return string value even set type="number" when use getValues("count").
For the string values of name="count", my custom function increment doesn't work I expected. when I clicked + button, it return with string added.
import React, { FC, useEffect } from 'react';
import * as Styled from './style';
import { useForm, ErrorMessage} from 'react-hook-form';
import { ItemCountForm } from 'src/models/item-count';
export const CountForm:FC<{
partialData : Omit<ItemCountForm,'count'>
}> = ({
partialData
}) => {
const { register, handleSubmit, errors,getValues, setValue } = useForm<{count:number}>({
defaultValues:{
count: 1}
});
const onSubmit = async(data: {count: number}) => {
console.log('submitted');
const formData: ItemCountForm = {
id: partialData.id,
name: partialData.name,
count: data.count,
price: partialData.price * data.count
}
console.log(formData);
}
const count = getValues('count');
const onIncrease = () => count < 999 && setValue('count',Number(count) + 1);
const onDecrease = () => count > 1 && setValue('count',count - 1);
return(
<>
<form onSubmit={handleSubmit(onSubmit)}>
<input type="number" name="count" ref={register({
min:{
value:1,
message: "you need at least 1"
},
max: {
value: 999,
message: "you can have at most 999"
}
})}/>
<ErrorMessage
errors={errors}
name={"count"}
as={<Styled.ErrorText/>}
/>
<button onClick={onIncrease}>+</button>
<button onClick={onDecrease}>-</button>
<button type="submit">Add Cart</button>
</form>
</>
)
}
An onChange
event on an input of type number will give you the string corresponding to the entered number. That is a browser behaviour. When you are trying to update the value you need to parse the value to an integer and then update
const onIncrease = () => count < 999 && setValue('count',parseInt(count) + 1);
const onDecrease = () => count > 1 && setValue('count',parseInt(count) - 1);