Basic usage
|
|
-
Create BoxDB instance
1 2 3 4 5 6 7// src/database/index.ts import BoxDB from 'bxd'; export const DATABASE_NAME = 'database'; export const VERSION = 1; export const database = new BoxDB(DATABASE_NAME, VERSION); -
Define Box
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20// src/models/user.ts import BoxDB, { BoxData } from 'bxd'; import { database } from '../database'; const schema = { _id: { type: BoxDB.Types.NUMBER, key: true, }, name: BoxDB.Types.STRING, address: BoxDB.Types.STRING, hobby: BoxDB.Types.ARRAY, created_at: BoxDB.Types.DATE, updated_at: BoxDB.Types.DATE, } as const; const User = database.create('user', schema); export type UserType = BoxData<typeof schema>; export default User; -
Setup boxes entry source
1 2// src/models/index.ts export { default as User } from './user'; -
Open database before using boxes
1 2 3 4// src/index.ts import { database } from './database'; await database.open(); -
Done!
1 2 3 4import { User } from 'src/models'; await User.get(1); ...
React
-
Continuing from basic setup
-
Create react context and provider
1 2 3 4 5 6 7 8// context.ts import { createContext, ReactElement } from 'react'; import { database } from './index'; export const BoxContext = createContext(database); export const BoxProvider = ({ children }: { children: ReactElement }) => { return <BoxContext.Provider value={database}>{children}</BoxContext.Provider>; }; -
Setup provider
1 2 3<BoxProvider> ... </BoxProvider> -
Using BoxDB context
1 2 3 4import { useContext } from 'react'; import { BoxContext } from 'path/to/context.ts'; const db = useContext(BoxContext);
Demo
- Any Note: Simple note web application
- Hash Worker: Find hash via Web Worker and store task history to IndexedDB