0.1.8 ā€¢ Published 4 years ago

ismounted v0.1.8

Weekly downloads
2,003
License
MIT
Repository
github
Last release
4 years ago

isMounted

āš› hook to check if your component is still mounted

Changing the state in an unmounted component will result in an error like this:

Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.

But in some cases (promises derived from an api call, timeouts or intervals...) it's impossible to know if the component is still mounted or not.

šŸ˜Ž Use this hook and avoid errors

import React, { useState, useEffect } from 'react';
import useIsMounted from 'ismounted';
import myService from './myService';
import Loading from './Loading';
import ResultsView from './ResultsView';

const MySecureComponent = () => {
  const isMounted = useIsMounted();
  const [results, setResults] = useState(null);

  useEffect(() => {
    myService.getResults().then(val => {
      if (isMounted.current) {
        setResults(val);
      }
    });
  }, [myService.getResults]);

  return results ? <ResultsView results={results} /> : <Loading />;
};

export default MySecureComponent;

Installing

npm install ismounted or yarn add ismounted

0.1.8

4 years ago

0.1.7

4 years ago

0.1.6

4 years ago

0.1.5

4 years ago

0.1.4

4 years ago

0.1.3

4 years ago

0.1.2

4 years ago

0.1.1

5 years ago

0.1.0

5 years ago

0.0.2

5 years ago

0.0.1

5 years ago