Advertisement
libardorengifo

Untitled

Jan 14th, 2021
1,037
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { useState, useEffect, useRef } from "react";
  2.  
  3. export default function useMounted(parseToJson = true) {
  4.   const [isLoading, setIsLoading] = useState(false);
  5.   const [isError, setIsError] = useState(false);
  6.   const [error, setError] = useState(null);
  7.   const [data, setData] = useState(null);
  8.   const isMounted = useRef(true);
  9.  
  10.   const setErrors = (hasError = false, errorDesc = null) => {
  11.     setError(errorDesc);
  12.     setIsError(hasError);
  13.   };
  14.  
  15.   const setState = ({
  16.     hasError = false,
  17.     error = null,
  18.     loading = false,
  19.     _data = null,
  20.   }) => {
  21.     if (isMounted.current) {
  22.       if (hasError) {
  23.         setErrors(true, error);
  24.         setIsLoading(false);
  25.         return;
  26.       }
  27.       setErrors();
  28.       setIsLoading(loading);
  29.       setData(_data);
  30.     }
  31.   };
  32.  
  33.   const init = (promise) => {
  34.     if (!(promise instanceof Promise)) {
  35.       throw new TypeError("The `promise` argument is not of type promise");
  36.     }
  37.     setState({ loading: true });
  38.     promise.then(
  39.       async (res) => {
  40.         if (parseToJson) {
  41.           setState({ loading: false, _data: await res.json() });
  42.         } else {
  43.           setState({ loading: false, _data: res });
  44.         }
  45.       },
  46.       (error) => setState({ hasError: true, error })
  47.     );
  48.   };
  49.  
  50.   useEffect(() => () => (isMounted.current = false), []);
  51.  
  52.   return {
  53.     init,
  54.     isLoading,
  55.     isError,
  56.     error,
  57.     data,
  58.   };
  59. }
  60.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement