Idomatic way to ignore `finally` block after cancelling network request Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?
retrieve food groups from food item list
After Sam didn't return home in the end, were he and Al still friends?
What does Turing mean by this statement?
How to force a browser when connecting to a specific domain to be https only using only the client machine?
What does it mean that physics no longer uses mechanical models to describe phenomena?
How many time has Arya actually used Needle?
Relating to the President and obstruction, were Mueller's conclusions preordained?
Differences to CCompactSize and CVarInt
Central Vacuuming: Is it worth it, and how does it compare to normal vacuuming?
How does the math work when buying airline miles?
Asymptotics question
Would color changing eyes affect vision?
Understanding p-Values using an example
two integers one line calculator
Tannaka duality for semisimple groups
Why are vacuum tubes still used in amateur radios?
How can a team of shapeshifters communicate?
Why weren't discrete x86 CPUs ever used in game hardware?
GDP with Intermediate Production
License to disallow distribution in closed source software, but allow exceptions made by owner?
How to ternary Plot3D a function
Flight departed from the gate 5 min before scheduled departure time. Refund options
Can you force honesty by using the Speak with Dead and Zone of Truth spells together?
Moving a wrapfig vertically to encroach partially on a subsection title
Idomatic way to ignore `finally` block after cancelling network request
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
In React, it is quite common for me to have something similar to the following.
async componentDidMount()
try
this.setState( isLoading: true )
const data = await axios.get('...')
this.setState( data )
catch(error)
handleError(error)
finally
this.setState( isLoading: false )
This is great because the cleanup code (isLoading: false
) is DRY. That is, until I try to cancel network requests on unmount. That code would look like this:
async componentDidMount()
try
this.axiosCancelTokenSource = axios.CancelToken.source()
this.setState( isLoading: true )
const data = await axios.get('...',
cancelToken: this.axiosCancelTokenSource.token,
)
this.setState( data )
catch(error)
if (axios.isCancel(error)) return
handleError(error)
finally
this.setState( isLoading: false )
componentWillUnmount()
if (this.axiosCancelTokenSource) this.axiosCancelTokenSource()
The problem with this is that it will setState
after the component unmounts, which React will warn againts.
As far as I see it, these are my options for dealing with this:
Ignore the warning.
React gives a warning when yousetState
after unmount because it indicates a memory leak (in this case, the lingering network request, if not cancelled). If the network request is cancelled, there is still asetState
after unmount, but just to set a flag. There is no more lingering network request. It should be safe to ignore the warning in this case, but it doesn't feel right.Check what error was thrown in the
finally
block and add the sameif
statement as thecatch
block. This seems incredibly hacky and would require extra code to save the error from the catch block.Check if the component is mounted in the
finally
block. This is also hacky and requires boilerplate code to update athis.isMounted
flag.Put the cleanup code at the end of
try
and after the condition incatch
. This is not DRY. Humans are also very forgetful; I cannot count how many times I have forgotten to setisLoading = false
in catch.Define a
cleanup()
function before thetry
and call it intry
andcatch
. This is a decent option, but requires extra function calls, making it harder to follow.
So far, it looks like the first or fifth options are best, depending on how much you care about seeing warning messages. Am I missing any good options?
react.js axios
$endgroup$
add a comment |
$begingroup$
In React, it is quite common for me to have something similar to the following.
async componentDidMount()
try
this.setState( isLoading: true )
const data = await axios.get('...')
this.setState( data )
catch(error)
handleError(error)
finally
this.setState( isLoading: false )
This is great because the cleanup code (isLoading: false
) is DRY. That is, until I try to cancel network requests on unmount. That code would look like this:
async componentDidMount()
try
this.axiosCancelTokenSource = axios.CancelToken.source()
this.setState( isLoading: true )
const data = await axios.get('...',
cancelToken: this.axiosCancelTokenSource.token,
)
this.setState( data )
catch(error)
if (axios.isCancel(error)) return
handleError(error)
finally
this.setState( isLoading: false )
componentWillUnmount()
if (this.axiosCancelTokenSource) this.axiosCancelTokenSource()
The problem with this is that it will setState
after the component unmounts, which React will warn againts.
As far as I see it, these are my options for dealing with this:
Ignore the warning.
React gives a warning when yousetState
after unmount because it indicates a memory leak (in this case, the lingering network request, if not cancelled). If the network request is cancelled, there is still asetState
after unmount, but just to set a flag. There is no more lingering network request. It should be safe to ignore the warning in this case, but it doesn't feel right.Check what error was thrown in the
finally
block and add the sameif
statement as thecatch
block. This seems incredibly hacky and would require extra code to save the error from the catch block.Check if the component is mounted in the
finally
block. This is also hacky and requires boilerplate code to update athis.isMounted
flag.Put the cleanup code at the end of
try
and after the condition incatch
. This is not DRY. Humans are also very forgetful; I cannot count how many times I have forgotten to setisLoading = false
in catch.Define a
cleanup()
function before thetry
and call it intry
andcatch
. This is a decent option, but requires extra function calls, making it harder to follow.
So far, it looks like the first or fifth options are best, depending on how much you care about seeing warning messages. Am I missing any good options?
react.js axios
$endgroup$
add a comment |
$begingroup$
In React, it is quite common for me to have something similar to the following.
async componentDidMount()
try
this.setState( isLoading: true )
const data = await axios.get('...')
this.setState( data )
catch(error)
handleError(error)
finally
this.setState( isLoading: false )
This is great because the cleanup code (isLoading: false
) is DRY. That is, until I try to cancel network requests on unmount. That code would look like this:
async componentDidMount()
try
this.axiosCancelTokenSource = axios.CancelToken.source()
this.setState( isLoading: true )
const data = await axios.get('...',
cancelToken: this.axiosCancelTokenSource.token,
)
this.setState( data )
catch(error)
if (axios.isCancel(error)) return
handleError(error)
finally
this.setState( isLoading: false )
componentWillUnmount()
if (this.axiosCancelTokenSource) this.axiosCancelTokenSource()
The problem with this is that it will setState
after the component unmounts, which React will warn againts.
As far as I see it, these are my options for dealing with this:
Ignore the warning.
React gives a warning when yousetState
after unmount because it indicates a memory leak (in this case, the lingering network request, if not cancelled). If the network request is cancelled, there is still asetState
after unmount, but just to set a flag. There is no more lingering network request. It should be safe to ignore the warning in this case, but it doesn't feel right.Check what error was thrown in the
finally
block and add the sameif
statement as thecatch
block. This seems incredibly hacky and would require extra code to save the error from the catch block.Check if the component is mounted in the
finally
block. This is also hacky and requires boilerplate code to update athis.isMounted
flag.Put the cleanup code at the end of
try
and after the condition incatch
. This is not DRY. Humans are also very forgetful; I cannot count how many times I have forgotten to setisLoading = false
in catch.Define a
cleanup()
function before thetry
and call it intry
andcatch
. This is a decent option, but requires extra function calls, making it harder to follow.
So far, it looks like the first or fifth options are best, depending on how much you care about seeing warning messages. Am I missing any good options?
react.js axios
$endgroup$
In React, it is quite common for me to have something similar to the following.
async componentDidMount()
try
this.setState( isLoading: true )
const data = await axios.get('...')
this.setState( data )
catch(error)
handleError(error)
finally
this.setState( isLoading: false )
This is great because the cleanup code (isLoading: false
) is DRY. That is, until I try to cancel network requests on unmount. That code would look like this:
async componentDidMount()
try
this.axiosCancelTokenSource = axios.CancelToken.source()
this.setState( isLoading: true )
const data = await axios.get('...',
cancelToken: this.axiosCancelTokenSource.token,
)
this.setState( data )
catch(error)
if (axios.isCancel(error)) return
handleError(error)
finally
this.setState( isLoading: false )
componentWillUnmount()
if (this.axiosCancelTokenSource) this.axiosCancelTokenSource()
The problem with this is that it will setState
after the component unmounts, which React will warn againts.
As far as I see it, these are my options for dealing with this:
Ignore the warning.
React gives a warning when yousetState
after unmount because it indicates a memory leak (in this case, the lingering network request, if not cancelled). If the network request is cancelled, there is still asetState
after unmount, but just to set a flag. There is no more lingering network request. It should be safe to ignore the warning in this case, but it doesn't feel right.Check what error was thrown in the
finally
block and add the sameif
statement as thecatch
block. This seems incredibly hacky and would require extra code to save the error from the catch block.Check if the component is mounted in the
finally
block. This is also hacky and requires boilerplate code to update athis.isMounted
flag.Put the cleanup code at the end of
try
and after the condition incatch
. This is not DRY. Humans are also very forgetful; I cannot count how many times I have forgotten to setisLoading = false
in catch.Define a
cleanup()
function before thetry
and call it intry
andcatch
. This is a decent option, but requires extra function calls, making it harder to follow.
So far, it looks like the first or fifth options are best, depending on how much you care about seeing warning messages. Am I missing any good options?
react.js axios
react.js axios
asked 3 mins ago
MarcelMarcel
1255
1255
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217802%2fidomatic-way-to-ignore-finally-block-after-cancelling-network-request%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217802%2fidomatic-way-to-ignore-finally-block-after-cancelling-network-request%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown