grungnet/src/contexts/DatabaseContext.js

83 lines
2.4 KiB
JavaScript
Raw Normal View History

import React, { useState, useEffect } from "react";
2020-11-25 23:24:33 -05:00
import { Box, Text } from "theme-ui";
import Banner from "../components/Banner";
import { getDatabase } from "../database";
const DatabaseContext = React.createContext();
export function DatabaseProvider({ children }) {
const [database, setDatabase] = useState();
const [databaseStatus, setDatabaseStatus] = useState("loading");
2020-11-25 23:24:33 -05:00
const [databaseError, setDatabaseError] = useState();
useEffect(() => {
// Create a test database and open it to see if indexedDB is enabled
let testDBRequest = window.indexedDB.open("__test");
2020-10-23 07:16:18 -04:00
testDBRequest.onsuccess = async function () {
testDBRequest.result.close();
2020-10-23 07:16:18 -04:00
let db = getDatabase({ autoOpen: false });
setDatabase(db);
2020-10-23 07:16:18 -04:00
db.on("ready", () => {
setDatabaseStatus("loaded");
});
await db.open();
window.indexedDB.deleteDatabase("__test");
};
// If indexedb disabled create an in memory database
testDBRequest.onerror = async function () {
console.warn("Database is disabled, no state will be saved");
const indexedDB = await import("fake-indexeddb");
const IDBKeyRange = await import("fake-indexeddb/lib/FDBKeyRange");
2020-10-23 07:16:18 -04:00
let db = getDatabase({ indexedDB, IDBKeyRange, autoOpen: false });
setDatabase(db);
2020-10-23 07:16:18 -04:00
db.on("ready", () => {
setDatabaseStatus("disabled");
});
await db.open();
window.indexedDB.deleteDatabase("__test");
};
2020-11-25 23:24:33 -05:00
function handleDatabaseError(event) {
if (event.reason.name === "QuotaExceededError") {
event.preventDefault();
setDatabaseError({
name: event.reason.name,
message: "Storage Quota Exceeded Please Clear Space and Try Again.",
});
}
}
window.addEventListener("unhandledrejection", handleDatabaseError);
return () => {
window.removeEventListener("unhandledrejection", handleDatabaseError);
};
}, []);
const value = {
database,
databaseStatus,
2020-11-25 23:24:33 -05:00
databaseError,
};
return (
<DatabaseContext.Provider value={value}>
2020-11-25 23:24:33 -05:00
<>
{children}
<Banner
isOpen={!!databaseError}
onRequestClose={() => setDatabaseError()}
>
<Box p={1}>
<Text as="p" variant="body2">
{databaseError && databaseError.message}
</Text>
</Box>
</Banner>
</>
</DatabaseContext.Provider>
);
}
export default DatabaseContext;