From bf6bd17a4d005c69ad2c3571b37c9a646e058a8d Mon Sep 17 00:00:00 2001 From: Lukas Tyla Date: Tue, 19 Nov 2024 15:21:29 +0200 Subject: [PATCH] [pickers] Ensure internal value timezone is updated (#15435) --- .../tests/timezone.MobileTimePicker.test.tsx | 16 ++++++++++++++++ .../internals/hooks/usePicker/usePickerValue.ts | 13 +++++++++++++ 2 files changed, 29 insertions(+) diff --git a/packages/x-date-pickers/src/MobileTimePicker/tests/timezone.MobileTimePicker.test.tsx b/packages/x-date-pickers/src/MobileTimePicker/tests/timezone.MobileTimePicker.test.tsx index bba289a72d10..306b4dad76c5 100644 --- a/packages/x-date-pickers/src/MobileTimePicker/tests/timezone.MobileTimePicker.test.tsx +++ b/packages/x-date-pickers/src/MobileTimePicker/tests/timezone.MobileTimePicker.test.tsx @@ -21,5 +21,21 @@ describe(' - Timezone', () => { expect(screen.getByTestId('hours')).to.have.text('11'); }); + + it('should use the updated timezone prop for the value displayed in the toolbar', () => { + const { setProps } = render( + , + ); + + expect(screen.getByTestId('hours')).to.have.text('03'); + + setProps({ timezone: 'America/New_York' }); + + expect(screen.getByTestId('hours')).to.have.text('11'); + }); }); }); diff --git a/packages/x-date-pickers/src/internals/hooks/usePicker/usePickerValue.ts b/packages/x-date-pickers/src/internals/hooks/usePicker/usePickerValue.ts index f24d9e11a718..5550807e7502 100644 --- a/packages/x-date-pickers/src/internals/hooks/usePicker/usePickerValue.ts +++ b/packages/x-date-pickers/src/internals/hooks/usePicker/usePickerValue.ts @@ -172,6 +172,7 @@ export const usePickerValue = < const { current: defaultValue } = React.useRef(inDefaultValue); const { current: isControlled } = React.useRef(inValueWithoutRenderTimezone !== undefined); + const [previousTimezoneProp, setPreviousTimezoneProp] = React.useState(timezoneProp); /* eslint-disable react-hooks/rules-of-hooks, react-hooks/exhaustive-deps */ if (process.env.NODE_ENV !== 'production') { @@ -240,6 +241,18 @@ export const usePickerValue = < }; }); + const timezoneFromDraftValue = valueManager.getTimezone(utils, dateState.draft); + if (previousTimezoneProp !== timezoneProp) { + setPreviousTimezoneProp(timezoneProp); + + if (timezoneProp && timezoneFromDraftValue && timezoneProp !== timezoneFromDraftValue) { + setDateState((prev) => ({ + ...prev, + draft: valueManager.setTimezone(utils, timezoneProp, prev.draft), + })); + } + } + const { getValidationErrorForNewValue } = useValidation({ props, validator,