Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Overview
This PR fixes instances in the app where we attempt to perform state updates on unmounted components. It resolves issue #228.
Occasionally, when we navigate away from a layout on the CMS, or close a modal before it's done loading something, we receive the following error message in the console:
The problem arises when we are awaiting some async operation, and setting state after the async operation completes. For example, I might be in the
EditPage
layout, and after I retrieve the page's content, I set that content into the component state.The problem is that if I navigate away from the
EditPage
layout while it is retrieving the content (the async operation), theEditPage
component unmounts, but thecomponentWillMount
function, or theuseEffect
function will continue to run and attempt to set state after the async operation completes. This is why we get the error message about updating state on an unmounted component.Solution
The solution is to only set state when we can be sure that the component is mounted. We can do this by introducing an
_isMounted
local variable, which is set totrue
when the async operation is run, but also define a cleanup function (either within theuseEffect
or ascomponentWillUnmount
) which sets the_isMounted
variable tofalse
. Since state updates are only performed when_isMounted
istrue
, we no longer attempt to update state after a component is unmounted. The caveat is that_isMounted
needs to be defined as a normal variable, and not as state, since it needs to be updated synchronously for this to work.