fix: handle clearing of number field to send null instead of undefined (#22537)

* fix: handle clearing of number field to send null instead of undefined

set number field to null when cleared; undefined prevented clearing.

* test: add test for clearing integer field to set it to null

---------

Co-authored-by: Rémi de Juvigny <8087692+remidej@users.noreply.github.com>
This commit is contained in:
Dhruv Maradiya 2025-01-07 15:09:51 +05:30 committed by GitHub
parent 110b429be2
commit 7d767aba20
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 28 additions and 3 deletions

View File

@ -9,7 +9,7 @@ import { InputProps } from './types';
const NumberInputImpl = forwardRef<HTMLInputElement, InputProps>(
({ name, required, label, hint, labelAction, type, ...props }, ref) => {
const field = useField<number>(name);
const field = useField<number | null>(name);
const fieldRef = useFocusInputField<HTMLInputElement>(name);
const composedRefs = useComposedRefs(ref, fieldRef);
@ -20,10 +20,12 @@ const NumberInputImpl = forwardRef<HTMLInputElement, InputProps>(
<NumberInput
ref={composedRefs}
onValueChange={(value) => {
field.onChange(name, value);
// Convert undefined to null to store it in the form state
// See https://github.com/strapi/strapi/issues/22533
field.onChange(name, value ?? null);
}}
step={type === 'float' || type == 'decimal' ? 0.01 : 1}
value={field.value}
value={field.value ?? undefined}
{...props}
/>
<Field.Hint />

View File

@ -92,4 +92,27 @@ describe('Test type integer', () => {
field: 543,
});
});
test('Clearing the value should set it to null', async () => {
const res = await rq.post('/content-manager/collection-types/api::withinteger.withinteger', {
body: {
field: 123,
},
});
const updatedRes = await rq.put(
`/content-manager/collection-types/api::withinteger.withinteger/${res.body.data.documentId}`,
{
body: {
field: null,
},
}
);
expect(updatedRes.statusCode).toBe(200);
expect(updatedRes.body.data).toMatchObject({
documentId: res.body.data.documentId,
field: null,
});
});
});