Develop a React app using SKDB¶
SKDB fits perfectly with React allowing you to build end-to-end reactive applications.
The skdb-react
npm
package provides a couple
of React hooks to make using SKDB very convenient.
Inject an SKDB instance in to your app so that you can query and modify data wherever you need to¶
You can wrap your app in an SKDBProvider
React
Context.
This lets you pass an SKDB object in to your component tree without
needing to thread it through everything using React props. You can
access the instance at anytime using the
useSKDB()
hook.
import { SKDBProvider } from "skdb-react";
import { createSkdb } from "skdb";
const skdb = await createSkdb({asWorker: false});
ReactDOM.createRoot(document.getElementById('root')!).render(
<SKDBProvider skdb={skdb}>
<App />
</SKDBProvider>
);
Watch an SKDB SQL query in a react component and re-render when it changes¶
skdb-react
provides a useQuery()
React hook. Use this within
components to get the results of a query. useQuery()
automatically
sets up a watch
ed query that updates React state, causing the
component to reactively re-render whenever query results change.
Get hold of the SKDB instance in a react component to modify data¶
You can retrieve the SKDB object passed in via SKDBProvider
using
the useSKDB()
React hook.
This is useful for modifying the database in response to user actions.
Show a floating development console on your page to inspect data and test queries¶
Instead of using SKDBProvider
, you can use SKDBDevConsoleProvider
during development. This provides a floating component on the page
that can be used to watch and test queries. You can also use the dev
console to quickly switch between users and test privacy rules.
Here's an example:
import { createSkdb } from "skdb";
import { SKDBDevConsoleProvider } from "skdb-react";
import { createLocalDbConnectedTo, skdbDevServerDb } from "skdb-dev";
const skdb = await createSkdb({asWorker: false});
const connect = async (accessKey: string = "root") => {
const remoteDb = await skdbDevServerDb("example");
return await createLocalDbConnectedTo(remoteDb, accessKey);
}
ReactDOM.createRoot(document.getElementById('root')!).render(
<SKDBDevConsoleProvider skdbAsRoot={skdb} create={connect}>
<App />
</SKDBDevConsoleProvider>
);