mirror of
https://github.com/shishantbiswas/bknd.git
synced 2026-03-16 04:27:21 +00:00
104 lines
2.5 KiB
Plaintext
104 lines
2.5 KiB
Plaintext
---
|
|
title: 'Remix'
|
|
description: 'Run bknd inside Remix'
|
|
---
|
|
import InstallBknd from '/snippets/install-bknd.mdx';
|
|
|
|
## Installation
|
|
Install bknd as a dependency:
|
|
<InstallBknd />
|
|
|
|
## Serve the API
|
|
Create a new api splat route file at `app/routes/api.$.ts`:
|
|
```ts
|
|
// app/routes/api.$.ts
|
|
import { serve } from "bknd/adapter/remix";
|
|
|
|
const handler = serve({
|
|
connection: {
|
|
url: "http://localhost:8080"
|
|
}
|
|
});
|
|
|
|
export const loader = handler;
|
|
export const action = handler;
|
|
```
|
|
For more information about the connection object, refer to the [Database](/usage/database) guide.
|
|
|
|
Now make sure that you wrap your root layout with the `ClientProvider` so that all components
|
|
share the same context:
|
|
```tsx
|
|
// app/root.tsx
|
|
import { withApi } from "bknd/adapter/remix"
|
|
import { type Api, ClientProvider } from "bknd/client";
|
|
|
|
export function Layout(props) {
|
|
// nothing to change here, just for orientation
|
|
return (
|
|
<html>{/* ... */}</html>
|
|
);
|
|
}
|
|
|
|
// add the api to the `AppLoadContext`
|
|
// so you don't have to manually type it again
|
|
declare module "@remix-run/server-runtime" {
|
|
export interface AppLoadContext {
|
|
api: Api;
|
|
}
|
|
}
|
|
|
|
// export a loader that initiates the API
|
|
// and passes it down to args.context.api
|
|
export const loader = withApi(async (args: LoaderFunctionArgs, api: Api) => {
|
|
return {
|
|
user: api.getUser()
|
|
};
|
|
});
|
|
|
|
export default function App() {
|
|
const { user } = useLoaderData<typeof loader>();
|
|
return (
|
|
<ClientProvider user={user}>
|
|
<Outlet />
|
|
</ClientProvider>
|
|
);
|
|
}
|
|
```
|
|
|
|
## Enabling the Admin UI
|
|
Create a new splat route file at `app/routes/admin.$.tsx`:
|
|
```tsx
|
|
// app/routes/admin.$.tsx
|
|
import { adminPage } from "bknd/adapter/remix";
|
|
import "bknd/dist/styles.css";
|
|
|
|
export default adminPage({
|
|
config: { basepath: "/admin" }
|
|
});
|
|
```
|
|
|
|
## Example usage of the API
|
|
Since the API has already been constructed in the root layout, you can now use it in any page:
|
|
```tsx
|
|
// app/routes/_index.tsx
|
|
import type { LoaderFunctionArgs } from "@remix-run/server-runtime";
|
|
import { useLoaderData } from "@remix-run/react";
|
|
|
|
export const loader = async ({ context: { api } }: LoaderFunctionArgs) => {
|
|
const { data } = await api.data.readMany("todos");
|
|
return { data, user: api.getUser() };
|
|
};
|
|
|
|
export default function Index() {
|
|
const { data, user } = useLoaderData<typeof loader>();
|
|
|
|
return (
|
|
<div>
|
|
<h1>Data</h1>
|
|
<pre>{JSON.stringify(data, null, 2)}</pre>
|
|
<h1>User</h1>
|
|
<pre>{JSON.stringify(user, null, 2)}</pre>
|
|
</div>
|
|
);
|
|
}
|
|
``` |