Fix for RelatedModelField (#6657)

- Cache initial data in memo
- Fixes https://github.com/inventree/InvenTree/issues/6654
This commit is contained in:
Oliver 2024-03-07 23:13:57 +11:00 committed by GitHub
parent d842942fa9
commit 8aab19b578
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -43,6 +43,7 @@ export function RelatedModelField({
const [offset, setOffset] = useState<number>(0);
const [initialData, setInitialData] = useState<{}>({});
const [data, setData] = useState<any[]>([]);
const dataRef = useRef<any[]>([]);
@ -61,17 +62,15 @@ export function RelatedModelField({
const url = `${definition.api_url}${field.value}/`;
api.get(url).then((response) => {
const data = response.data;
if (data && data.pk) {
if (response.data && response.data.pk) {
const value = {
value: data.pk,
data: data
value: response.data.pk,
data: response.data
};
setData([value]);
setInitialData(value);
dataRef.current = [value];
setPk(data.pk);
setPk(response.data.pk);
}
});
} else {
@ -208,10 +207,14 @@ export function RelatedModelField({
};
}, [definition]);
const currentValue = useMemo(
() => pk !== null && data.find((item) => item.value === pk),
[pk, data]
);
const currentValue = useMemo(() => {
if (!pk) {
return null;
}
let _data = [...data, initialData];
return _data.find((item) => item.value === pk);
}, [pk, data]);
// Field doesn't follow Mantine theming
// Define color theme to pass to field based on Mantine theme
@ -278,7 +281,6 @@ export function RelatedModelField({
onMenuScrollToBottom={() => setOffset(offset + limit)}
onMenuOpen={() => {
setIsOpen(true);
setValue('');
resetSearch();
selectQuery.refetch();
}}