### Install npm packages and start development server Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/to-do-app.mdx Navigates into the newly created project directory, installs all required npm dependencies, and then starts the local development server. ```bash cd project-name npm i npm run dev ``` -------------------------------- ### Install dependencies and start React development server Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/create-lofi-app.mdx Navigate into the project directory, install necessary npm packages, and then start the development server to run the React application locally. ```bash # first, cd into your project cd project-name # then, install all packages npm i # start your server npm run dev ``` -------------------------------- ### Install Basic React SDK Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/basic-react-sdk.mdx This snippet shows how to navigate into your project directory, install all existing npm packages, and then install the `@basictech/react` library using npm. ```bash # first, cd into your project cd project-name # then, install all packages npm i # finally, install Basic npm install @basictech/react ``` -------------------------------- ### Install Basic CLI and authenticate Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/to-do-app.mdx Installs the Basic CLI globally via npm, enabling interaction with Basic services. After installation, `basic login` initiates the authentication process, redirecting the user to sign up or log in to a Basic account in their browser. ```bash npm install -g @basictech/cli basic login ``` -------------------------------- ### Create a new local-first project Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/to-do-app.mdx Initializes a new local-first project using `create-lofi-app`. Users will be prompted to install Vite, name the project, and choose the Basic + Tailwind variant. ```bash npx create-lofi-app ``` -------------------------------- ### Fetch Project Details (JavaScript) Source: https://github.com/basicdb/basic-docs/blob/main/get-started/adminportal.mdx This JavaScript code snippet demonstrates how to make a sample GET request to the Basic API to retrieve project details. It requires replacing placeholders for and with your actual credentials. This request can be used to verify successful setup and connectivity to your Basic database. ```javascript fetch("https://api.basic.tech/project/", { headers: { "Authorization": "Bearer " } }).then(response => response.json()) .then(data => console.log(data)); ``` -------------------------------- ### Install @basictech/expo Package Source: https://github.com/basicdb/basic-docs/blob/main/basic-expo-rn/basic-rn-sdk.mdx Installs the `@basictech/expo` library using npm, providing core functionalities for integrating BasicTech services into a React Native project. ```bash npm install @basictech/expo ``` -------------------------------- ### Create a new local-first project with create-lofi-app Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/create-lofi-app.mdx This command initializes a new local-first project using `create-lofi-app`. Users will be prompted to install Vite, name their project, and select the Basic + Tailwind variant. ```bash npx create-lofi-app ``` -------------------------------- ### Install Basic CLI Globally Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/react-cli.mdx Installs the Basic CLI globally on your system using npm, making it accessible from any directory. ```bash npm i -g @basictech/cli ``` -------------------------------- ### Replace App.tsx with a clean slate Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/to-do-app.mdx Replaces the existing code in `src/App.tsx` with a minimal React component, providing a clean starting point for building the To-Do app UI. ```tsx import './App.css' function App() { return ( <>

my lofi to-do app

) } export default App ``` -------------------------------- ### Install Basic CLI Globally Source: https://github.com/basicdb/basic-docs/blob/main/get-started/cli.mdx Installs the Basic CLI package globally using npm, making the 'basic' command available in your terminal. ```bash npm i -g @basictech/cli ``` -------------------------------- ### Install the Basic CLI globally Source: https://github.com/basicdb/basic-docs/blob/main/basic-restapi/api-cli.mdx Installs the Basic command-line interface globally on your system using npm, allowing access to Basic commands from any directory. ```bash npm i -g @basictech/cli ``` -------------------------------- ### Example Web App Manifest for PWA Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/react-pwa.mdx A basic `manifest.json` file providing metadata for a Progressive Web App, including name, short name, start URL, display mode, theme colors, and icons. ```json { "name": "My PWA", "short_name": "PWA", "start_url": "/index.html", "display": "standalone", "background_color": "#FFFFFF", "theme_color": "#000000", "icons": [ { "src": "icon-192x192.png", "sizes": "192x192", "type": "image/png" }, { "src": "icon-512x512.png", "sizes": "512x512", "type": "image/png" } ] } ``` -------------------------------- ### Configure Basic Schema in basic.config.ts Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/basic-react-sdk.mdx This snippet demonstrates how to define the schema for your Basic project within the `basic.config.ts` file. It includes a `project_id`, `version`, and an example `tables` definition with a collection and a string field. ```typescript export const schema = { project_id: 'YOUR_PROJECT_ID', version: 0, tables: { table_name: { type: 'collection', fields: { field_name: { type: 'string', indexed: true } } } } } ``` -------------------------------- ### Example Simple Service Worker for Caching Source: https://github.com/basicdb/basic-docs/blob/main/readings/pwa.mdx A basic JavaScript service worker implementation that caches specified assets upon installation and serves them from cache for subsequent fetch requests, enabling offline support. ```javascript self.addEventListener('install', (event) => { event.waitUntil( caches.open('my-cache').then((cache) => { return cache.addAll([ '/', '/index.html', '/styles.css', '/script.js', '/icon-192x192.png', '/icon-512x512.png' ]); }) ); }); self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then((response) => { return response || fetch(event.request); }) ); }); ``` -------------------------------- ### Install Basic CLI Globally Source: https://github.com/basicdb/basic-docs/blob/main/basic-expo-rn/rn-cli.mdx Installs the Basic CLI package globally on your system using npm, making the 'basic' command available in your terminal. ```bash npm i -g @basictech/cli ``` -------------------------------- ### Initialize or integrate a Basic project with CLI Source: https://github.com/basicdb/basic-docs/blob/main/basic-restapi/api-cli.mdx Guides you through setting up a new Basic project or integrating an existing one within your current directory. This involves navigating to the project and running the initialization command. ```bash cd project-name ``` ```bash basic init ``` -------------------------------- ### Delete Database Item in React Source: https://github.com/basicdb/basic-docs/blob/main/sdk-reference/react-db.mdx Provides an example of deleting an item from the database using the `.delete()` method, requiring the item's ID, and handling the promise. ```tsx import { useBasic } from '@basictech/react' import { useState } from 'react' function App() { const { db } = useBasic() // Use .delete() to delete items // Include the ID of the item you want to delete const deleteItem = () => { db.collection('tablename').delete('ID_OF_ITEM') .then(console.log("Successfully deleted item")) .catch(error => console.error("Error deleting item: ", error)) } return ( <> {/* render delete button */} ) } ``` -------------------------------- ### Fetch Basic Project Details using JavaScript Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/react-adminportal.mdx This JavaScript snippet demonstrates how to make a sample GET request to the Basic API to retrieve project details. It requires replacing placeholders for `` and `` with your actual project ID and API key. This helps verify the API connection and ensure everything is working correctly. ```javascript fetch("https://api.basic.tech/project/", { headers: { "Authorization": "Bearer " } }).then(response => response.json()) .then(data => console.log(data)); ``` -------------------------------- ### Basic Schema Configuration Example Source: https://github.com/basicdb/basic-docs/blob/main/readings/schema.mdx This snippet shows a complete example of a Basic schema, including `project_id`, `version`, and definitions for `comments` and `items` tables with their respective fields. It demonstrates how to declare collections, string, number, and boolean types, and set fields as indexed. ```javascript export const schema = { project_id: '1234567890', version: 0, tables: { comments: { type: 'collection', fields: { title: { type: 'string', indexed: true }, body: { type: 'string', indexed: true }, rating: { type: 'number', indexed: true } } }, items: { type: 'collection', fields: { name: { type: 'string', indexed: true }, quantity: { type: 'number', indexed: true }, available: { type: 'boolean', indexed: true } } } } } ``` -------------------------------- ### Example Basic Schema Configuration Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/react-schema.mdx This snippet demonstrates a complete Basic schema configuration, showing how `project_id`, `version`, `tables`, and `fields` are structured. It includes examples of `comments` and `items` tables with various field types (`string`, `number`, `boolean`) and indexing. ```javascript export const schema = { project_id: '1234567890', version: 0, tables: { comments: { type: 'collection', fields: { title: { type: 'string', indexed: true }, body: { type: 'string', indexed: true }, rating: { type: 'number', indexed: true } } }, items: { type: 'collection', fields: { name: { type: 'string', indexed: true }, quantity: { type: 'number', indexed: true }, available: { type: 'boolean', indexed: true } } } } } ``` -------------------------------- ### Example Basic Schema Configuration Source: https://github.com/basicdb/basic-docs/blob/main/basic-restapi/api-schema.mdx This snippet shows a complete example of a Basic schema configuration, including `project_id`, `version`, and multiple tables with their fields and types. It demonstrates the JSON-like structure for defining collections and their respective string, number, and boolean fields with indexing. ```javascript export const schema = { project_id: '1234567890', version: 0, tables: { comments: { type: 'collection', fields: { title: { type: 'string', indexed: true }, body: { type: 'string', indexed: true }, rating: { type: 'number', indexed: true } } }, items: { type: 'collection', fields: { name: { type: 'string', indexed: true }, quantity: { type: 'number', indexed: true }, available: { type: 'boolean', indexed: true } } } } } ``` -------------------------------- ### Basic Schema Configuration Example Source: https://github.com/basicdb/basic-docs/blob/main/basic-expo-rn/rn-schema.mdx An example `basic.config.ts` file demonstrating a complete schema declaration for a Basic project. It includes top-level parameters, defines two collections ('comments' and 'items'), and specifies their respective fields with data types and indexing status. ```javascript export const schema = { project_id: '1234567890', version: 0, tables: { comments: { type: 'collection', fields: { title: { type: 'string', indexed: true }, body: { type: 'string', indexed: true }, rating: { type: 'number', indexed: true } } }, items: { type: 'collection', fields: { name: { type: 'string', indexed: true }, quantity: { type: 'number', indexed: true }, available: { type: 'boolean', indexed: true } } } } } ``` -------------------------------- ### Connect to a new Basic project Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/to-do-app.mdx Uses the Basic CLI to connect the local project to a new Basic project. Users are prompted to create a new project, give it a name, and select the 'typescript' template. ```bash basic init ``` -------------------------------- ### Go: Implement Token Validation and Refresh for API Access Source: https://github.com/basicdb/basic-docs/blob/main/basic-restapi/basic-api.mdx This Go program provides functions to validate the expiration of a JWT access token and to refresh an expired token using a refresh token. The `main` function illustrates the workflow: checking token validity, refreshing if needed, and then making an authenticated HTTP GET request to an API endpoint. ```Go package main import ( "fmt" "time" "net/http" "io/ioutil" "encoding/json" "github.com/golang-jwt/jwt/v5" ) type TokenResponse struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token"` } func refreshToken(refreshToken string) (*TokenResponse, error) { payload := map[string]string{ "refresh_token": refreshToken, } jsonData, _ := json.Marshal(payload) req, _ := http.NewRequest("POST", "https://api.basic.tech/auth/token", bytes.NewBuffer(jsonData)) req.Header.Set("Content-Type", "application/json") client := &http.Client{} resp, err := client.Do(req) if err != nil { return nil, err } defer resp.Body.Close() var tokenResp TokenResponse err = json.NewDecoder(resp.Body).Decode(&tokenResp) return &tokenResp, err } func isTokenValid(accessToken string) bool { token, _, err := jwt.NewParser().ParseUnverified(accessToken, jwt.MapClaims{}) if err != nil { return false } if claims, ok := token.Claims.(jwt.MapClaims); ok { exp := claims["exp"].(float64) return int64(exp) > time.Now().Unix() } return false } func main() { if isTokenValid(accessToken) { // Token is valid, proceed with API calls req, _ := http.NewRequest("GET", "https://api.basic.tech/your-endpoint", nil) req.Header.Add("Authorization", "Bearer "+accessToken); client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) } else { // Token is invalid, refresh it newTokens, err := refreshToken(refreshToken) if err != nil { fmt.Println("Error refreshing token:", err) return } accessToken = newTokens.AccessToken refreshToken = newTokens.RefreshToken // Now use the new access token req, _ := http.NewRequest("GET", "https://api.basic.tech/your-endpoint", nil) req.Header.Add("Authorization", "Bearer "+accessToken); client := &http.Client{} resp, _ := client.Do(req) defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) fmt.Println(string(body)) } } ``` -------------------------------- ### Example Web App Manifest File Source: https://github.com/basicdb/basic-docs/blob/main/readings/pwa.mdx A sample `manifest.json` file demonstrating essential metadata for a Progressive Web App, including name, display mode, colors, and icon definitions. ```json { "name": "My PWA", "short_name": "PWA", "start_url": "/index.html", "display": "standalone", "background_color": "#FFFFFF", "theme_color": "#000000", "icons": [ { "src": "icon-192x192.png", "sizes": "192x192", "type": "image/png" }, { "src": "icon-512x512.png", "sizes": "512x512", "type": "image/png" } ] } ``` -------------------------------- ### API: Get All Users in Project Source: https://github.com/basicdb/basic-docs/blob/main/api-reference/project-users/get-project-users.mdx This API endpoint allows retrieval of all users belonging to a specified project. It uses a GET request to the `/project/{id}/user/` path, where `{id}` is the unique identifier of the project. ```APIDOC openapi: get /project/{id}/user/ ``` -------------------------------- ### API Endpoint: GET /utils/slugify Source: https://github.com/basicdb/basic-docs/blob/main/api-reference/utils/convert-text-to-url-friendly-slug.mdx Documents the GET /utils/slugify API endpoint, which is typically used for converting a given string into a URL-friendly slug format. ```APIDOC openapi: get /utils/slugify ``` -------------------------------- ### Fetch Basic Project Details Source: https://github.com/basicdb/basic-docs/blob/main/basic-expo-rn/rn-adminportal.mdx This JavaScript snippet demonstrates how to make a GET request to the Basic API to retrieve project details. It requires replacing placeholders for your project ID and API key, which should be kept confidential and used in a secure server environment. ```js fetch("https://api.basic.tech/project/", { headers: { "Authorization": "Bearer " } }).then(response => response.json()) .then(data => console.log(data)); ``` -------------------------------- ### Simplify React homepage in App.tsx Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/create-lofi-app.mdx This diff shows how to remove the default `create-lofi-app` boilerplate from `App.tsx` and replace it with a simple 'my lofi app' heading, demonstrating basic UI customization. ```typescript - import { useBasic, useQuery } from '@basictech/react' import './App.css' - const deleteCursorIcon = `url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMjQgMjQiIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzYwQTVGkEiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cG9seWxpbmUgcG9pbnRzPSIzIDYgNSA2IDIxIDYiPjwvcG9seWxpbmU+PHBhdGggZD0iTTE5IDZ2MTRhMiAyIDAgMCAxLTIgMkg3YTIgMiAwIDAgMS0yLTJWNm0zIDBWNGEyIDIgMCAwIDEgMi0yaDRhMiAyIDAgMCAxIDIgMnYyIj48L3BhdGg+PC9zdmc+),auto` function App() { - const { db } = useBasic() - const emojis = useQuery(() => db.collection('emojis').getAll()) return ( <> +

my lofi app

-

create-lofi-app

-
- -
- {emojis?.map((e: { id: string, value: string }) => ( -
db.collection('emojis').delete(e.id)}> - {e.value} -
- ))} -
-
- - ) } export default App ``` -------------------------------- ### Fetch Project Details using JavaScript Source: https://github.com/basicdb/basic-docs/blob/main/basic-restapi/api-adminportal.mdx This JavaScript code snippet demonstrates how to make a GET request to the Basic API to retrieve project details. It requires replacing `` and `` with your actual credentials. The API key should be kept secret and used only in secure server environments. ```js fetch("https://api.basic.tech/project/", { headers: { "Authorization": "Bearer " } }).then(response => response.json()) .then(data => console.log(data)); ``` -------------------------------- ### Retrieve All Admin Projects Source: https://github.com/basicdb/basic-docs/blob/main/api-reference/projects/get-all-admin-projects.mdx This API endpoint allows users to retrieve a list of all projects where they have administrator privileges. It uses the HTTP GET method to query the /project/ path. ```APIDOC GET /project/ ``` -------------------------------- ### OpenAPI Root GET Endpoint Source: https://github.com/basicdb/basic-docs/blob/main/api-reference/get-.mdx Defines a basic OpenAPI GET endpoint at the root path, typically used for health checks or basic service information. ```APIDOC openapi: get / ``` -------------------------------- ### Wrap React App with BasicProvider Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/basic-react-sdk.mdx This snippet shows how to integrate the `BasicProvider` into your `src/main.tsx` file. It imports `BasicProvider` and the `schema` from `basic.config`, then wraps the main `App` component to provide Basic context, requiring your project ID and schema. ```tsx // add the BasicProvider to your existing imports import { BasicProvider } from '@basictech/react' import { schema } from '../basic.config' createRoot(document.getElementById('root')).render( {/* Wrap your app in BasicProvider, including the project ID and schema */} , ) ``` -------------------------------- ### Get all records from a database table using Expo / RN SDK Source: https://github.com/basicdb/basic-docs/blob/main/sdk-reference/expo-rn.mdx Retrieves all records from the specified database table using `getAll()`. This method returns a query builder for further chaining operations like filtering and ordering. ```js const allNotes = await db.from('notes').getAll(); ``` -------------------------------- ### Push schema changes to Basic DB Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/to-do-app.mdx Executes the Basic CLI command to push the locally defined schema changes from `basic.config.ts` to the Basic database, updating the project's data structure. ```bash basic push ``` -------------------------------- ### Define To-Do app schema in basic.config.ts Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/to-do-app.mdx Modifies the `src/basic.config.ts` file to define the data schema for the To-Do application. It sets up a 'todos' collection with 'name' (string) and 'completed' (boolean) fields. ```tsx export const schema = { project_id: "your-project-id", version: 0, tables: { todos: { type: "collection", fields: { name: { type: "string" }, completed: { type: "boolean" } } } } } ``` -------------------------------- ### Add input and button to To-Do app UI Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/to-do-app.mdx Enhances the `App.tsx` component by adding an input field and a button, along with basic Tailwind CSS styling, to create the core UI elements for adding to-dos. ```tsx import './App.css' function App() { return (

my lofi to-do app

) } export default App ``` -------------------------------- ### Retrieve All Project Keys Source: https://github.com/basicdb/basic-docs/blob/main/api-reference/project-keys/get-all-keys.mdx This API endpoint allows you to retrieve a list of all API keys associated with a specific project. The project is identified by its unique ID. ```APIDOC get /project/{id}/key ``` -------------------------------- ### Configure Basic.tech schema in basic.config.ts Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/create-lofi-app.mdx This diff demonstrates how to update the `basic.config.ts` file to define a custom schema for your project, replacing the default 'emojis' collection with a new 'your_table_name' collection and its fields. ```typescript export const schema = { project_id: '', version: 0, tables: { + your_table_name: { + type: 'collection', + fields: { + your_field_name: { + type: 'string', + }, + }, - emojis: { - type: 'collection', - fields: { - value: { - type: 'string', - }, - }, - }, }, } ``` -------------------------------- ### OpenAPI GET /project/slug Endpoint Definition Source: https://github.com/basicdb/basic-docs/blob/main/api-reference/projects/check-project-slug-availability.mdx Defines a basic OpenAPI path for a GET request to '/project/slug'. This snippet is a fragment of an OpenAPI specification, indicating an endpoint to fetch project information by its slug. ```APIDOC openapi: get /project/slug ``` -------------------------------- ### Configure Basic Project ID and Schema Version Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/create-lofi-app.mdx To enable local-first sync and authentication, update your `basic.config.ts` file with your project's unique ID and the current schema version. This configuration links your application to your Basic project, allowing data synchronization and user management. ```typescript export const schema = { project_id: 'Update this with YOUR_PROJECT_ID', version: 'your updated schema version', tables: { ... } } ``` -------------------------------- ### API methods for paginating database results Source: https://github.com/basicdb/basic-docs/blob/main/basic-restapi/api-filtering.mdx Describes the `limit` and `offset` methods used as query parameters for the Basic.tech database API to control the number of results returned and the starting point. ```APIDOC Methods: limit(count) offset(count) ``` -------------------------------- ### Database Interaction Functions API Source: https://github.com/basicdb/basic-docs/blob/main/sdk-reference/react-db.mdx API reference for the database interaction methods available through `db.collection('tablename')`. ```APIDOC db.collection('tablename').get('ID_OF_ITEM') description: Fetch a single item from the table. Returns a promise, or can be used with `useQuery` to "subscribe" to data changes. db.collection('tablename').getAll() description: Fetch all items from the table. Returns a promise, or can be used with `useQuery` to "subscribe" to data changes. notes: Filtering is not supported yet, conduct any filtering in your client logic. Joins are not supported yet, manually fetch information from the separate tables and join them in your client logic. db.collection('tablename').add({ 'item': 'value' }) description: Adds a new item to the table, returns a promise with the new item. db.collection('tablename').update({ 'id': 'ID_OF_ITEM', 'value': { 'item': 'value' } }) description: Updates an item in the table, returns a promise with the updated item. db.collection('tablename').delete('ID_OF_ITEM') description: Deletes an item from the table, returns a promise. ``` -------------------------------- ### Database Table Methods API Reference (Expo / RN SDK) Source: https://github.com/basicdb/basic-docs/blob/main/sdk-reference/expo-rn.mdx Comprehensive API documentation for the methods available on a database table instance, accessed via `db.from(*table_name*)`. These methods facilitate common CRUD operations on database records. ```APIDOC db.from(tableName: string) .getAll(): QueryBuilder Description: Retrieves all records from the specified table. Returns: Query builder for chaining (e.g., filtering, ordering). .get(id: string): Record | throws Description: Fetches a single record by its ID. Parameters: id: The unique identifier of the record. Returns: The record object, or throws an error if not found. .add(value: object): Record Description: Inserts a new record into the table. Parameters: value: The object representing the new record data. Returns: The newly added record object. .update(id: string, value: object): void Description: Updates an existing record identified by its ID with partial data. Parameters: id: The unique identifier of the record to update. value: An object containing the fields to update. .replace(id: string, value: object): void Description: Completely replaces an existing record identified by its ID with a new complete record. Parameters: id: The unique identifier of the record to replace. value: The complete object to replace the existing record with. .delete(id: string): void Description: Deletes a record from the table by its ID. Parameters: id: The unique identifier of the record to delete. ``` -------------------------------- ### Read Database Items with useQuery and Promises in React Source: https://github.com/basicdb/basic-docs/blob/main/sdk-reference/react-db.mdx Demonstrates two methods for reading data from the database: using `useQuery` for real-time subscriptions to all items, and using a promise-based approach with `.get()` for fetching a single item by ID. ```tsx import { useBasic, useQuery } from '@basictech/react' import { useState } from 'react' function App() { // Import db from useBasic() inside your React component const { db } = useBasic() // Example 1: Use useQuery to "subscribe" to data from the database const items = useQuery(() => db.collection('tablename').getAll()) // Example 2: Or get a single item by ID. You could use async instead of useQuery if you need it only once const [singleItem, setSingleItem] = useState(null) const getItem = () => { db.collection('tablename').get('ID_OF_ITEM') .then(item => { setSingleItem(item) console.log("Successfully fetched single item: ", item) }) .catch(error => console.error("Error fetching single item: ", error)) } return ( <> {/* render items */} ) } ``` -------------------------------- ### Integrate BasicProvider into React Native App Source: https://github.com/basicdb/basic-docs/blob/main/basic-expo-rn/basic-rn-sdk.mdx Wraps the root of a React Native application with the `BasicProvider` component from `@basictech/expo`. This provides the application with access to the BasicTech client and authentication context, using the defined schema and project ID. ```tsx // App.tsx import { BasicProvider } from '@basictech/expo'; import { schema } from './basic.config'; import MainApp from './MainApp'; export default function App() { return ( ); } ``` -------------------------------- ### Supported query operators for Basic.tech API Source: https://github.com/basicdb/basic-docs/blob/main/basic-restapi/api-filtering.mdx This table lists all supported operators for filtering database results via the Basic.tech API, including their descriptions and example usage in query parameters. ```APIDOC Operator | Description | Example ---------|-------------|-------- eq | Equality | status=eq.active neq | Not equal | status=neq.deleted gt | Greater than| priority=gt.3 gte | Greater than or equal| priority=gte.3 lt | Less than | priority=lt.3 lte | Less than or equal| priority=lte.3 like | Pattern (case sensitive)| title=like.*project* ilike | Pattern (case insensitive)| title=ilike.*todo* in | Value in set| tags=in.work,important not | Negation | tags=not.eq.work ``` -------------------------------- ### Redirect Users to Basic Auth Page Source: https://github.com/basicdb/basic-docs/blob/main/basic-restapi/basic-api.mdx This snippet demonstrates how to create a redirect to the Basic Auth page, requiring parameters like `client_id`, `redirect_uri`, `response_type`, `scope`, and `state`. The redirect URL template is provided, and users must replace placeholder values. ```cURL curl --request GET \ --url 'https://api.basic.tech/auth/authorize?response_type=code&redirect_uri='YOUR_REDIRECT_URI'&scope=profile&state='YOUR_STATE'&client_id='YOUR_CLIENT_ID'' ``` ```Python import requests url = "https://api.basic.tech/auth/authorize" querystring = {"response_type":"code","client_id":"YOUR_CLIENT_ID","redirect_uri":"YOUR_REDIRECT_URI","scope":"profile","state":"YOUR_STATE"} response = requests.request("GET", url, params=querystring) print(response.text) ``` ```JavaScript const options = {method: 'GET'}; fetch('https://api.basic.tech/auth/authorize?response_type=code&client_id='YOUR_CLIENT_ID'&redirect_uri='YOUR_REDIRECT_URI'&scope=profile&state='YOUR_STATE'', options) .then(response => response.json()) .then(response => console.log(response)) .catch(err => console.error(err)); ``` ```PHP "https://api.basic.tech/auth/authorize?response_type=code&client_id='YOUR_CLIENT_ID'&redirect_uri='YOUR_REDIRECT_URI'&scope=profile&state='YOUR_STATE'", CURLOPT_RETURNTRANSFER => true, CURLOPT_ENCODING => "", CURLOPT_MAXREDIRS => 10, CURLOPT_TIMEOUT => 30, CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, CURLOPT_CUSTOMREQUEST => "GET" ]); $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; } ``` ```Go package main import ( "fmt" "net/http" "io/ioutil" ) func main() { url := "https://api.basic.tech/auth/authorize?response_type=code&client_id='YOUR_CLIENT_ID'&redirect_uri='YOUR_REDIRECT_URI'&scope=profile&state='YOUR_STATE'" req, _ := http.NewRequest("GET", url, nil) res, _ := http.DefaultClient.Do(req) defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) fmt.Println(res) fmt.Println(string(body)) } ``` ```Java HttpResponse response = Unirest.get("https://api.basic.tech/auth/authorize?response_type=code&client_id='YOUR_CLIENT_ID'&redirect_uri='YOUR_REDIRECT_URI'&scope=profile&state='YOUR_STATE'") .asString(); ``` -------------------------------- ### Initialize or Integrate a Basic Project Source: https://github.com/basicdb/basic-docs/blob/main/get-started/cli.mdx Navigates into a project directory and runs the 'basic init' command to either create a new Basic project or integrate an existing one, prompting for user choices. ```bash cd project-name basic init ``` -------------------------------- ### Access BasicTech Authentication and Database Client with useBasic Hook Source: https://github.com/basicdb/basic-docs/blob/main/basic-expo-rn/basic-rn-sdk.mdx Demonstrates how to use the `useBasic` hook from `@basictech/expo` within a React component. This hook provides access to the authenticated user, login/logout functions, the database client, and loading/signed-in states for managing user sessions and data interactions. ```tsx import { useBasic } from '@basictech/expo'; const { user, login, signout, db, isLoading, isSignedIn } = useBasic(); ``` ```APIDOC useBasic() hook properties: - user: The authenticated user or null. - login(): Starts the OAuth login flow. - signout(): Logs the user out, clearing all tokens. - db: The main database client. - isLoading: True during authentication state checks. - isSignedIn: Whether a user is authenticated. ``` -------------------------------- ### Define BasicTech Database Schema in TypeScript Source: https://github.com/basicdb/basic-docs/blob/main/basic-expo-rn/basic-rn-sdk.mdx Defines the database schema for BasicTech, specifying tables, field types, and indexing. This configuration is crucial for structuring data within your application and should be stored in a file like `src/basic.config.ts`. ```typescript // src/basic.config.ts export const schema = { project_id: 'YOUR_PROJECT_ID', // Replace with your actual project ID version: 1, tables: { // example table for a notes app notes: { type: 'collection', fields: { title: { type: 'string', indexed: true }, content: { type: 'string' }, createdAt: { type: 'number', indexed: true }, completed: { type: 'boolean', indexed: true }, priority: { type: 'number', indexed: true }, tags: { type: 'json', indexed: true } } }, // Add other tables here } }; ``` -------------------------------- ### Read and Display To-Do Tasks from Basic DB in React Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/to-do-app.mdx This snippet shows how to fetch and display all to-do tasks from Basic DB using the `useQuery` hook. It retrieves data from the 'todos' collection and renders each task, building upon the task submission functionality. ```tsx / add useQuery hook import import { useBasic, useQuery } from '@basictech/react' import { useState } from 'react' import './App.css' function App() { const { signin, signout, isSignedIn, user, db } = useBasic() const [taskInput, setTaskInput] = useState('') // get all tasks from the database const tasks = useQuery(() => db.collection('todos').getAll()) const addTask = () => { if (!taskInput.trim()) return db.collection('todos').add({ name: taskInput, completed: false }) .then((item: any) => { setTaskInput('') console.log("Successfully added new todo with ID: ", item) }) .catch((error: any) => { console.error("Error adding todo: ", error) }) } return (

my lofi to-do app

setTaskInput(e.target.value)} />
{/* Add the tasks list here */}
{tasks?.map((task: any) => (
{task.name}
))}
{isSignedIn ? (

Signed in as: {user?.email}

) : ( )}
) } export default App ``` -------------------------------- ### GET /auth/authorize API Endpoint Source: https://github.com/basicdb/basic-docs/blob/main/api-reference/auth/redirect-to-sign-in.mdx API endpoint for user authorization, typically used to redirect to a sign-in page. ```APIDOC openapi: get /auth/authorize ``` -------------------------------- ### React Component for Local-First To-Do App Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/to-do-app.mdx This React functional component demonstrates how to build a local-first to-do application. It uses `useState` for input management, `useQuery` to fetch and reactively update tasks from a local database, and functions (`addTask`, `deleteTask`) to interact with the database. It also includes UI for adding, deleting, and displaying tasks, along with user authentication (sign-in/out) integration. ```jsx const [taskInput, setTaskInput] = useState('') const tasks = useQuery(() => db.collection('todos').getAll()) const addTask = () => { if (!taskInput.trim()) return db.collection('todos').add({ name: taskInput, completed: false }) .then((item: any) => { setTaskInput('') console.log("Successfully added new todo with ID: ", item) }) .catch((error: any) => { console.error("Error adding todo: ", error) }) } // add the deleteTask function const deleteTask = (id: string) => { db.collection('todos').delete(id) } return (

my lofi to-do app

setTaskInput(e.target.value)} />
{/* update styling to add a delete button */}
{tasks?.map((task: any) => (
{task.name}
))}
{isSignedIn ? (

Signed in as: {user?.email}

) : ( )}
) } export default App ``` -------------------------------- ### View All Basic CLI Commands Source: https://github.com/basicdb/basic-docs/blob/main/get-started/cli.mdx Displays a comprehensive list of all available commands and their brief descriptions for the Basic CLI. ```bash basic help ``` -------------------------------- ### Add New Item to Database in React Source: https://github.com/basicdb/basic-docs/blob/main/sdk-reference/react-db.mdx Illustrates how to add a new item to a database table using the `.add()` method, handling the promise resolution to update component state. ```tsx import { useBasic } from '@basictech/react' import { useState } from 'react' function App() { const { db } = useBasic() // Use .add() to add items const [newItem, setNewItem] = useState(null) const addItem = () => { db.collection('tablename').add({ name: 'cutie' }) .then(item => { setNewItem(item) console.log("Successfully added new item with ID: ", item) }) .catch(error => console.error("Error adding new item: ", error)) } return ( <> {/* render newItem */} ) } ``` -------------------------------- ### Retrieving User JWT Token with useBasic Source: https://github.com/basicdb/basic-docs/blob/main/sdk-reference/react-hooks.mdx Demonstrates how to use the `getToken` async function from `useBasic` to fetch the user's JSON Web Token. The example shows how to call this function within an `onClick` handler using `await`. ```tsx import { useBasic } from '@basictech/react' function App() { const { getToken } = useBasic() return ( <> ) } ``` -------------------------------- ### Basic CLI Command Reference Source: https://github.com/basicdb/basic-docs/blob/main/get-started/cli.mdx A reference list of various Basic CLI commands for account management, project listing, version checking, and debugging. ```APIDOC basic account - Show account information basic logout - logout from your basic account basic status - Show login status basic projects - list your projects basic version - Show CLI version basic update - Update CLI to the latest version basic debug - Show Basic config directory location ``` -------------------------------- ### Retrieve User by Project and User ID (OpenAPI) Source: https://github.com/basicdb/basic-docs/blob/main/api-reference/project-users/get-user-details.mdx Defines the OpenAPI GET method for accessing a specific user's details within a given project. Requires both project ID and user ID as path parameters. ```APIDOC openapi: get /project/{id}/user/{user_id} ``` -------------------------------- ### Simple JavaScript Service Worker for PWA Caching Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/react-pwa.mdx A basic JavaScript service worker script that caches essential files upon installation and serves them from the cache for offline access, falling back to network if not found. ```javascript self.addEventListener('install', (event) => { event.waitUntil( caches.open('my-cache').then((cache) => { return cache.addAll([ '/', '/index.html', '/styles.css', '/script.js', '/icon-192x192.png', '/icon-512x512.png' ]); }) ); }); self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then((response) => { return response || fetch(event.request); }) ); }); ``` -------------------------------- ### Initialize or Integrate Basic Project Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/react-cli.mdx Runs the `basic init` command within your project directory to either create a new Basic project or integrate an existing one. The CLI will prompt you to choose your preferred option and configure your project. ```bash basic init ``` -------------------------------- ### Add Login and Logout Buttons to React App Source: https://github.com/basicdb/basic-docs/blob/main/basic-react/to-do-app.mdx This snippet demonstrates how to integrate user sign-in and sign-out functionality into a React application's `App.tsx` file using the `@basictech/react` library. It imports `signin`, `signout`, `isSignedIn`, and `user` hooks to manage authentication state and display appropriate UI elements based on the user's sign-in status, showing a sign-in button when logged out and user email with a sign-out button when logged in. ```tsx /// add back the UseBasic import import { useBasic } from '@basictech/react' import './App.css' function App() { // Import signin to enable the user to sign in // Import signout to enable the user to sign out // Import isSignedIn to check if the user is signed in // Import user to get the user's information once they're signed in const { signin, isSignedIn, user, signout } = useBasic() return (

my lofi to-do app

{/* if not signed in yet, show the sign in button */} {/* when signed in, show the user's email */} {isSignedIn ? (

Signed in as: {user?.email}

{/* Add a button to sign out */}
) : ( )}
) } export default App ```