Skip to content

Commit

Permalink
fix: Removed infinite loop in AltDateWidget
Browse files Browse the repository at this point in the history
Fixes rjsf-team#3516 by removing the infinite loop caused by two `useEffects()` by moving the code for one into the `onChange` handler
- Updated `AltDateWidget` to switch to a simple `useState()` rather than `useReducer()` and moved the code for one `useEffect()` into the `onChange` handler
  - This change makes the code match the `antd` and `chakra-ui` versions
- Updated the `CHANGELOG.md` accordingly
  • Loading branch information
heath-freenome committed Mar 17, 2023
1 parent 147a6a2 commit 69386a0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 17 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ should change the heading of the (upcoming) version to include a major version b
-->

# 5.3.1

## @rjsf/core

- Updated `AltDateWidget` to switch onChange handling of a single field to match the working code in `antd`, fixing [#3516](https://github.com/rjsf-team/react-jsonschema-form/issues/3516)

# 5.3.0

## @rjsf/antd
Expand Down
35 changes: 18 additions & 17 deletions packages/core/src/components/widgets/AltDateWidget.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { MouseEvent, useCallback, useEffect, useReducer } from 'react';
import { MouseEvent, useCallback, useEffect, useState } from 'react';
import {
ariaDescribedByIds,
parseDateString,
Expand Down Expand Up @@ -115,26 +115,27 @@ function AltDateWidget<T = any, S extends StrictRJSFSchema = RJSFSchema, F exten
value,
}: WidgetProps<T, S, F>) {
const { translateString } = registry;
const [state, setState] = useReducer((state: DateObject, action: Partial<DateObject>) => {
return { ...state, ...action };
}, parseDateString(value, time));
const [state, setState] = useState(parseDateString(value, time));

useEffect(() => {
if (value && value !== toDateString(state, time)) {
setState(parseDateString(value, time));
}
}, [value, state, time]);
setState(parseDateString(value, time));
}, [time, value]);

useEffect(() => {
if (readyForChange(state)) {
// Only propagate to parent state if we have a complete date{time}
onChange(toDateString(state, time));
}
}, [state, time, onChange]);
const handleChange = useCallback(
(property: keyof DateObject, value: string) => {
const nextState = {
...state,
[property]: typeof value === 'undefined' ? -1 : value,
};

const handleChange = useCallback((property: keyof DateObject, value: string) => {
setState({ [property]: value });
}, []);
if (readyForChange(nextState)) {
onChange(toDateString(nextState, time));
} else {
setState(nextState);
}
},
[onChange, state, time]
);

const handleSetNow = useCallback(
(event: MouseEvent<HTMLAnchorElement>) => {
Expand Down

0 comments on commit 69386a0

Please sign in to comment.