All files / src/contexts DatabaseContext.jsx

100% Statements 15/15
100% Branches 4/4
100% Functions 5/5
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53                        1x   1x 5x 5x   5x   3x 1x   1x 1x       5x 1x             4x 3x             1x             2x  
/**
 * DatabaseContext.jsx
 *
 * Simple provider that kicks off the Web Worker (and therefore the SQLite DB
 * initialisation) as soon as the app mounts.  Components import individual
 * functions from database.js directly — no React context is needed to pass
 * the DB instance around.
 */
import React, { createContext, useContext, useEffect, useState } from 'react';
import { getProducts } from '../db/api';
 
 
const DatabaseContext = createContext({ ready: false });
 
export const DatabaseProvider = ({ children }) => {
    const [ready, setReady] = useState(false);
    const [error, setError] = useState(null);
 
    useEffect(() => {
        // Use a lightweight ping (getProducts) to detect when the API is ready
        getProducts()
            .then(() => setReady(true))
            .catch((err) => {
                console.error('Failed to initialize DB', err);
                setError(err.message);
            });
    }, []);
 
    if (error) {
        return (
            <div style={{ padding: '20px', color: 'red', textAlign: 'center' }}>
                Erro ao carregar o banco de dados. Verifique o console.
            </div>
        );
    }
 
    if (!ready) {
        return (
            <div style={{ padding: '20px', textAlign: 'center' }}>
                Carregando banco de dados...
            </div>
        );
    }
 
    return (
        <DatabaseContext.Provider value={{ ready }}>
            {children}
        </DatabaseContext.Provider>
    );
};
 
export const useDatabase = () => useContext(DatabaseContext);