Wraps GET requests in useRequest in order to handle unmounting more gracefully if the requests are still pending.

This commit is contained in:
mabashian
2020-06-10 14:20:42 -04:00
parent a1d1a1078b
commit a71a9057a2

View File

@@ -1,4 +1,4 @@
import React, { Fragment, useState, useEffect, useCallback } from 'react'; import React, { Fragment, useEffect, useCallback } from 'react';
import { Link, useHistory } from 'react-router-dom'; import { Link, useHistory } from 'react-router-dom';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
import { t, Trans } from '@lingui/macro'; import { t, Trans } from '@lingui/macro';
@@ -47,44 +47,42 @@ function CredentialDetail({ i18n, credential }) {
user_capabilities, user_capabilities,
}, },
} = credential; } = credential;
const [fields, setFields] = useState([]);
const [inputSources, setInputSources] = useState({});
const [managedByTower, setManagedByTower] = useState([]);
const [contentError, setContentError] = useState(null);
const [hasContentLoading, setHasContentLoading] = useState(true);
const history = useHistory(); const history = useHistory();
useEffect(() => { const {
(async () => { result: { fields, managedByTower, inputSources },
setContentError(null); request: fetchDetails,
setHasContentLoading(true); isLoading: hasContentLoading,
try { error: contentError,
const [ } = useRequest(
{ useCallback(async () => {
data: { inputs: credentialTypeInputs, managed_by_tower }, const [
}, {
loadedInputSources, data: { inputs: credentialTypeInputs, managed_by_tower },
] = await Promise.all([ },
CredentialTypesAPI.readDetail(credential_type.id), loadedInputSources,
CredentialsAPI.readInputSources(credentialId), ] = await Promise.all([
]); CredentialTypesAPI.readDetail(credential_type.id),
CredentialsAPI.readInputSources(credentialId),
setFields(credentialTypeInputs.fields || []); ]);
setManagedByTower(managed_by_tower); return {
setInputSources( fields: credentialTypeInputs.fields || [],
loadedInputSources.reduce((inputSourcesMap, inputSource) => { managedByTower: managed_by_tower,
inputSources: loadedInputSources.reduce(
(inputSourcesMap, inputSource) => {
inputSourcesMap[inputSource.input_field_name] = inputSource; inputSourcesMap[inputSource.input_field_name] = inputSource;
return inputSourcesMap; return inputSourcesMap;
}, {}) },
); {}
} catch (error) { ),
setContentError(error); };
} finally { }, [credentialId, credential_type]),
setHasContentLoading(false); {
} fields: [],
})(); managedByTower: true,
}, [credential_type, credentialId]); inputSources: {},
}
);
const { const {
request: deleteCredential, request: deleteCredential,
@@ -173,6 +171,10 @@ function CredentialDetail({ i18n, credential }) {
); );
}; };
useEffect(() => {
fetchDetails();
}, [fetchDetails]);
if (hasContentLoading) { if (hasContentLoading) {
return <ContentLoading />; return <ContentLoading />;
} }