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