From 741c22929da504c991a919915ae4335a20849c17 Mon Sep 17 00:00:00 2001 From: Urmas Lamster Date: Thu, 11 Jun 2020 16:37:50 +0300 Subject: [PATCH] usePromise detects unmounted components. Currently, if a component using usePromise (or useFetch, which uses usePromise) is unmounted before the encapsulated work is complete. It will still try to update the react state and trigger an annoying warning in react dev mode. This wraps the state updates inside a check to see if the component is still mounted. --- usePromise.js | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/usePromise.js b/usePromise.js index 5408276..8dae57a 100644 --- a/usePromise.js +++ b/usePromise.js @@ -14,20 +14,32 @@ function usePromise ( if (!callFunction) { return } + + var isMounted = true; + function unMount () { + isMounted = false; + } + !state[0].isLoading && state[1]({ data: state[0].data, isLoading: true }) callFunction.apply(null, inputs) .then(function (data) { - state[1]({ - data: data, - isLoading: false - }) + if (isMounted) { + state[1]({ + data: data, + isLoading: false + }) + } }) .catch(function (error) { - state[1]({ - error: error, - isLoading: false - }) + if (isMounted) { + state[1]({ + error: error, + isLoading: false + }) + } }) + + return unMount; }, flattenInput(inputs)) return state[0]