Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: memory leaks in application #242

Merged
merged 4 commits into from
Nov 24, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 53 additions & 50 deletions src/components/ComponentSettingsModal.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -120,53 +120,58 @@ const ComponentSettingsModal = ({
}

useEffect(() => {
if (originalCategory) setCategory(originalCategory);

const baseUrl = `${process.env.REACT_APP_BACKEND_URL}/sites/${siteName}${originalCategory ? type === "resource" ? `/resources/${originalCategory}` : `/collections/${originalCategory}` : ''}`
setBaseApiUrl(baseUrl)

const fetchData = async () => {
// Retrieve the list of all page/resource categories for use in the dropdown options. Also sets the default category if none is specified.
if (type === 'resource') {
const resourcesResp = await axios.get(`${process.env.REACT_APP_BACKEND_URL}/sites/${siteName}/resources`);
const { resources } = resourcesResp.data;
setAllCategories(resources.map((category) => ({
value: category.dirName,
label: category.dirName,
})))
} else if (type === 'page') {
const collectionsResp = await axios.get(`${process.env.REACT_APP_BACKEND_URL}/sites/${siteName}/collections`);
const { collections } = collectionsResp.data;
const collectionCategories = [''].concat(collections) // allow for selection of "Unlinked Page" category
setAllCategories(collectionCategories.map((category) => (
{
value:category,
label:category ? category : 'Unlinked Page'
}
)))
}
let _isMounted = true

if (originalCategory) setCategory(originalCategory);

const baseUrl = `${process.env.REACT_APP_BACKEND_URL}/sites/${siteName}${originalCategory ? type === "resource" ? `/resources/${originalCategory}` : `/collections/${originalCategory}` : ''}`
setBaseApiUrl(baseUrl)

const fetchData = async () => {
// Retrieve the list of all page/resource categories for use in the dropdown options. Also sets the default category if none is specified.
if (type === 'resource') {
const resourcesResp = await axios.get(`${process.env.REACT_APP_BACKEND_URL}/sites/${siteName}/resources`);
const { resources } = resourcesResp.data;
if (_isMounted) setAllCategories(resources.map((category) => ({
value: category.dirName,
label: category.dirName,
})))
} else if (type === 'page') {
const collectionsResp = await axios.get(`${process.env.REACT_APP_BACKEND_URL}/sites/${siteName}/collections`);
const { collections } = collectionsResp.data;
const collectionCategories = [''].concat(collections) // allow for selection of "Unlinked Page" category
if (_isMounted) setAllCategories(collectionCategories.map((category) => (
{
value:category,
label:category ? category : 'Unlinked Page'
}
)))
}

// Set component form values
if (isNewFile) {
// Set default values for new file
// Set component form values
if (isNewFile) {
// Set default values for new file
if (_isMounted) {
setTitle('Title')
setPermalink('permalink')
if (type === 'resource') setResourceDate(new Date().toISOString().split("T")[0])

} else {
// Retrieve data from an existing page/resource
const resp = await axios.get(`${baseUrl}/pages/${fileName}`);
const { content, sha: fileSha } = resp.data;
const base64DecodedContent = Base64.decode(content);
const { frontMatter, mdBody } = frontMatterParser(base64DecodedContent);

let existingLink
if (frontMatter.permalink) {
// We want to set parts of the link by default, and only leave a portion editable by the user
const { editableLink } = retrieveCollectionAndLinkFromPermalink(frontMatter.permalink)
existingLink = editableLink
}

}

} else {
// Retrieve data from an existing page/resource
const resp = await axios.get(`${baseUrl}/pages/${fileName}`);
const { content, sha: fileSha } = resp.data;
const base64DecodedContent = Base64.decode(content);
const { frontMatter, mdBody } = frontMatterParser(base64DecodedContent);

let existingLink
if (frontMatter.permalink) {
// We want to set parts of the link by default, and only leave a portion editable by the user
const { editableLink } = retrieveCollectionAndLinkFromPermalink(frontMatter.permalink)
existingLink = editableLink
}

if (_isMounted) {
// File properties
setSha(fileSha)
setMdBody(mdBody)
Expand All @@ -183,14 +188,12 @@ const ComponentSettingsModal = ({
setResourceDate(frontMatter.date)
setOriginalThirdNavTitle(frontMatter.third_nav_title)
setThirdNavTitle(frontMatter.third_nav_title)
}
}
}
}
}

try {
fetchData()
} catch (err) {
console.log(err)
}
fetchData().catch((err) => console.log(err))
return () => { _isMounted = false }
}, [])

useEffect(() => {
Expand Down
24 changes: 18 additions & 6 deletions src/components/LoadingButton.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from 'react';
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';

export default function LoadingButton(props) {
Expand All @@ -14,16 +14,28 @@ export default function LoadingButton(props) {

// track whether button is loading or not
const [isLoading, setButtonLoading] = React.useState(false);

useEffect(() => {
let _isMounted = true

const runCallback = async () => {
await callback();
if (_isMounted) setButtonLoading(false);
}

if (isLoading) {
runCallback()
}

return () => { _isMounted = false }
}, [isLoading])

return (
<button
type="button"
className={isLoading ? `${className} ${disabledStyle}` : className}
disabled={isLoading ? true : disabled}
onClick={async () => {
setButtonLoading(true);
await callback();
setButtonLoading(false);
}}
onClick={() => setButtonLoading(true)}
// eslint-disable-next-line react/jsx-props-no-spreading
{...remainingProps}
>
Expand Down
42 changes: 22 additions & 20 deletions src/layouts/CategoryPages.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,30 +37,32 @@ const CategoryPages = ({ match, location, isResource }) => {
const [categoryPages, setCategoryPages] = useState()

useEffect(() => {
const fetchData = async () => {
if (isResource) {
const resourcePagesResp = await axios.get(`${process.env.REACT_APP_BACKEND_URL}/sites/${siteName}/resources/${collectionName}`);
const { resourcePages } = resourcePagesResp.data;
let _isMounted = true
const fetchData = async () => {
if (isResource) {
const resourcePagesResp = await axios.get(`${process.env.REACT_APP_BACKEND_URL}/sites/${siteName}/resources/${collectionName}`);
const { resourcePages } = resourcePagesResp.data;

if (resourcePages.length > 0) {
const retrievedResourcePages = resourcePages.map((resourcePage) => {
const { title, date } = retrieveResourceFileMetadata(resourcePage.fileName);
return {
title,
date,
fileName: resourcePage.fileName,
};
});
setCategoryPages(retrievedResourcePages)
} else {
setCategoryPages([])
}
if (resourcePages.length > 0) {
const retrievedResourcePages = resourcePages.map((resourcePage) => {
const { title, date } = retrieveResourceFileMetadata(resourcePage.fileName);
return {
title,
date,
fileName: resourcePage.fileName,
};
});
if (_isMounted) setCategoryPages(retrievedResourcePages)
} else {
const collectionsResp = await axios.get(`${BACKEND_URL}/sites/${siteName}/collections/${collectionName}`);
setCategoryPages(collectionsResp.data?.collectionPages)
if (_isMounted) setCategoryPages([])
}
} else {
const collectionsResp = await axios.get(`${BACKEND_URL}/sites/${siteName}/collections/${collectionName}`);
if (_isMounted) setCategoryPages(collectionsResp.data?.collectionPages)
}
fetchData()
}
fetchData()
return () => { _isMounted = false }
}, [])

return (
Expand Down
9 changes: 8 additions & 1 deletion src/layouts/EditHomepage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ const enumSection = (type, isErrorConstructor) => {
};

export default class EditHomepage extends Component {
_isMounted = false

constructor(props) {
super(props);
this.scrollRefs = [];
Expand Down Expand Up @@ -124,6 +126,7 @@ export default class EditHomepage extends Component {
}

async componentDidMount() {
this._isMounted = true
try {
const { match } = this.props;
const { siteName } = match.params;
Expand Down Expand Up @@ -195,7 +198,7 @@ export default class EditHomepage extends Component {
dropdownElems: dropdownElemsErrors,
};

this.setState({
if (this._isMounted) this.setState({
frontMatter,
originalFrontMatter: _.cloneDeep(frontMatter),
sha,
Expand All @@ -210,6 +213,10 @@ export default class EditHomepage extends Component {
}
}

componentWillUnmount() {
this._isMounted = false;
}

onFieldChange = async (event) => {
try {
const { state } = this;
Expand Down
9 changes: 8 additions & 1 deletion src/layouts/EditPage.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ const getBackButtonInfo = (resourceCategory, collectionName, siteName) => {
}

export default class EditPage extends Component {
_isMounted = true

constructor(props) {
super(props);
const { match, isResourcePage, isCollectionPage } = this.props;
Expand All @@ -113,6 +115,7 @@ export default class EditPage extends Component {
}

async componentDidMount() {
this._isMounted = true
try {
const resp = await axios.get(this.apiEndpoint);
const { content, sha } = resp.data;
Expand Down Expand Up @@ -146,7 +149,7 @@ export default class EditPage extends Component {
});
}

this.setState({
if (this._isMounted) this.setState({
csp,
sha,
originalMdValue: mdBody.trim(),
Expand All @@ -159,6 +162,10 @@ export default class EditPage extends Component {
}
}

componentWillUnmount() {
this._isMounted = false;
}

updatePage = async () => {
try {
const { state } = this;
Expand Down
9 changes: 8 additions & 1 deletion src/layouts/Files.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import MediaCard from '../components/media/MediaCard';
import MediaSettingsModal from '../components/media/MediaSettingsModal';

export default class Files extends Component {
_isMounted = false

constructor(props) {
super(props);
this.state = {
Expand All @@ -21,19 +23,24 @@ export default class Files extends Component {
}

async componentDidMount() {
this._isMounted = true
try {
const { match } = this.props;
const { siteName } = match.params;
const resp = await axios.get(`${process.env.REACT_APP_BACKEND_URL}/sites/${siteName}/documents`, {
withCredentials: true,
});
const files = resp.data.documents;
this.setState({ files });
if (this._isMounted) this.setState({ files });
} catch (err) {
console.log(err);
}
}

componentWillUnmount() {
this._isMounted = false;
}

onFileSelect = async (event) => {
const fileReader = new FileReader();
const fileName = event.target.files[0].name;
Expand Down
9 changes: 8 additions & 1 deletion src/layouts/Images.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import MediaCard from '../components/media/MediaCard';
import MediaSettingsModal from '../components/media/MediaSettingsModal';

export default class Images extends Component {
_isMounted = false

constructor(props) {
super(props);
this.state = {
Expand All @@ -21,19 +23,24 @@ export default class Images extends Component {
}

async componentDidMount() {
this._isMounted = true
try {
const { match } = this.props;
const { siteName } = match.params;
const resp = await axios.get(`${process.env.REACT_APP_BACKEND_URL}/sites/${siteName}/images`, {
withCredentials: true,
});
const { images } = resp.data;
this.setState({ images });
if (this._isMounted) this.setState({ images });
} catch (err) {
console.log(err);
}
}

componentWillUnmount() {
this._isMounted = false;
}

uploadImage = async (imageName, imageContent) => {
try {
// toggle state so that image renaming modal appears
Expand Down
Loading