Add ability to properly cast a string, number, null to an integer (#990)

This commit is contained in:
Charles Bochet
2023-07-29 21:06:03 -07:00
committed by GitHub
parent 55be401204
commit fc7380e0b8
4 changed files with 164 additions and 41 deletions

View File

@ -6,6 +6,10 @@ import { IconUsers } from '@/ui/icon';
import { InplaceInputText } from '@/ui/inplace-input/components/InplaceInputText';
import { RecoilScope } from '@/ui/recoil-scope/components/RecoilScope';
import { Company, useUpdateOneCompanyMutation } from '~/generated/graphql';
import {
canBeCastAsIntegerOrNull,
castAsIntegerOrNull,
} from '~/utils/cast-as-integer-or-null';
type OwnProps = {
company: Pick<Company, 'id' | 'employees'>;
@ -27,30 +31,25 @@ export function CompanyEmployeesEditableField({ company }: OwnProps) {
}
async function handleSubmit() {
if (!internalValue) return;
try {
const numberValue = parseInt(internalValue);
if (isNaN(numberValue)) {
throw new Error('Not a number');
}
await updateCompany({
variables: {
where: {
id: company.id,
},
data: {
employees: numberValue,
},
},
});
setInternalValue(numberValue.toString());
} catch {
if (!canBeCastAsIntegerOrNull(internalValue)) {
handleCancel();
return;
}
const valueCastedAsNumberOrNull = castAsIntegerOrNull(internalValue);
await updateCompany({
variables: {
where: {
id: company.id,
},
data: {
employees: valueCastedAsNumberOrNull,
},
},
});
setInternalValue(valueCastedAsNumberOrNull?.toString());
}
async function handleCancel() {