diff --git a/src/app/components/Indicator/Indicator.tsx b/src/app/components/Indicator/Indicator.tsx index 6a41875..82ab3f7 100644 --- a/src/app/components/Indicator/Indicator.tsx +++ b/src/app/components/Indicator/Indicator.tsx @@ -1,6 +1,8 @@ import * as React from "react"; import "./indicator.css"; +import { useOsVersion } from './useOsVersion'; // Import the custom hook + // @ts-ignore import check from "../../icons/check.png"; import { launchPiecesOS } from "../../utils/launchPiecesOS"; @@ -13,7 +15,14 @@ interface IndicatorProps { // be green or red depending on the current status. export const Indicator = React.memo(({ isConnected }: IndicatorProps): React.JSX.Element => { - const osVersion = localStorage.getItem("version"); + const {osVersion, updateOsVersion, error} = useOsVersion(); // Destructuring the returned values + + if (error) { + console.error("Error with localStorage:", error); + // Display a user-friendly error message + return (
Error retrieving OS version.
); + } + return ( <>
diff --git a/src/app/components/Indicator/useOsVersion.tsx b/src/app/components/Indicator/useOsVersion.tsx new file mode 100644 index 0000000..4bbddc4 --- /dev/null +++ b/src/app/components/Indicator/useOsVersion.tsx @@ -0,0 +1,54 @@ +import { useState, useEffect } from 'react'; + +function isQuotaExceededError(err: unknown): boolean { + return ( + err instanceof DOMException && + // for everything except Firefox + (err.code === 22 || + // for Firefox + err.code === 1014 || + // testing name field too, because code might not be present + // for everything except Firefox + err.name === "QuotaExceededError" || + // for Firefox + err.name === "NS_ERROR_DOM_QUOTA_REACHED") + ); + } + +export const useOsVersion = () => { + const [osVersion, setOsVersion] = useState(null); + const [error, setError] = useState(null); + + useEffect(() => { + // Try-catch block to handle potential localStorage errors + try { + const storedVersion = localStorage.getItem("version"); + setOsVersion(storedVersion); + } catch (err) { + console.log(err); + setError("Error retrieving OS version from localStorage"); + } + }, []); + + // Function to update the stored version + const updateOsVersion = (newVersion: string) => { + try { + localStorage.setItem("version", newVersion); + setOsVersion(newVersion); + } catch (err) { + console.log(err); + if (isQuotaExceededError(err)) { + // Case where there wasn't enough space to store the item in localStorage. + setError("Not enough space in localStorage"); + + // Can use different storage mechanism (in-memory, a remote db, etc.) + } else { + // Case where the localStorage API is not supported. + setError("Error updating OS version in localStorage."); + } + + } + }; + + return {osVersion, updateOsVersion, error}; // Returning state, update function, and error +} \ No newline at end of file