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,19 +47,15 @@ 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,
} = useRequest(
useCallback(async () => {
const [ const [
{ {
data: { inputs: credentialTypeInputs, managed_by_tower }, data: { inputs: credentialTypeInputs, managed_by_tower },
@@ -69,22 +65,24 @@ function CredentialDetail({ i18n, credential }) {
CredentialTypesAPI.readDetail(credential_type.id), CredentialTypesAPI.readDetail(credential_type.id),
CredentialsAPI.readInputSources(credentialId), CredentialsAPI.readInputSources(credentialId),
]); ]);
return {
setFields(credentialTypeInputs.fields || []); fields: credentialTypeInputs.fields || [],
setManagedByTower(managed_by_tower); managedByTower: managed_by_tower,
setInputSources( inputSources: loadedInputSources.reduce(
loadedInputSources.reduce((inputSourcesMap, inputSource) => { (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,
inputSources: {},
} }
})(); );
}, [credential_type, credentialId]);
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 />;
} }