> ## Documentation Index
> Fetch the complete documentation index at: https://docs.basic.tech/llms.txt
> Use this file to discover all available pages before exploring further.

# Database (get, add, update, delete, etc.)

# Overview

There are 7 methods you can use to interact with the database.

They are used in conjunction with the `db` property from the `useBasic()` hook, and are appended in the format of `db.collection('tablename').METHOD()`.

## Methods

### .get()

<ParamField query=".get(id: string)" type="Promise<T | null>">
  Fetch a single item from the table by its ID. Returns `null` if not found.
</ParamField>

### .getAll()

<ParamField query=".getAll()" type="Promise<T[]>">
  Fetch all items from the table. Returns an empty array if no items exist.
</ParamField>

<Info>
  In the **React / Next.js client SDK** (sync or remote mode), `.getAll()` loads items for that collection and `.filter()` applies your predicate **on the client** after fetch. For **server-side query parameters** on HTTP, use the [REST API filtering guide](/basic-restapi/api-filtering) against the PDS endpoints instead.
</Info>

### .add()

<ParamField query=".add(data: Omit<T, 'id'>)" type="Promise<T>">
  Adds a new item to the table. The `id` is automatically generated by the server. Returns the created object with its new ID.
</ParamField>

### .put()

<ParamField query=".put(data: T)" type="Promise<T>">
  Upsert (insert or replace) an item. The `data` object **must include an `id` field**. If an item with that ID exists, it will be replaced entirely. If not, a new item will be created. Returns the upserted object.
</ParamField>

### .update()

<ParamField query=".update(id: string, data: Partial<T>)" type="Promise<T | null>">
  Partially update an existing item by ID. Only the fields you provide will be updated—other fields remain unchanged. Returns the updated object, or `null` if the item was not found.
</ParamField>

### .delete()

<ParamField query=".delete(id: string)" type="Promise<boolean>">
  Deletes an item from the table by ID. Returns `true` if deleted, `false` if the item was not found.
</ParamField>

### .filter()

<ParamField query=".filter(fn: (item: T) => boolean)" type="Promise<T[]>">
  Filter records using a predicate function. This fetches all records and filters client-side. Returns an array of matching objects.
</ParamField>

***

# Examples

### Read items

There are 2 ways to read items from the database:

* `.get('ID_OF_ITEM')`: Fetches a single item by ID
* `.getAll()`: Fetches all items from the table

```tsx App.tsx theme={null}
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
  // This will automatically re-render when data changes
  const items = useQuery(() => db.collection('tablename').getAll())
  
  // Example 2: Or get a single item by ID using async/await
  const [singleItem, setSingleItem] = useState(null)
  const getItem = async () => {
    const item = await db.collection('tablename').get('ID_OF_ITEM')
    if (item) {
      setSingleItem(item)
      console.log("Successfully fetched item: ", item)
    } else {
      console.log("Item not found")
    }
  }

  return (
    <>
      {/* render items */}
    </>
  )
}
```

### Add new item

```tsx App.tsx theme={null}
import { useBasic } from '@basictech/react'

function App() {
  const { db } = useBasic()

  // Use .add() to add items - id is auto-generated
  const addItem = async () => {
    const newItem = await db.collection('tablename').add({ name: 'cutie' })
    console.log("Created item with ID: ", newItem.id)
  }

  return (
    <>
      <button onClick={addItem}>Add Item</button>
    </>
  )
}
```

### Put (upsert) item

```tsx App.tsx theme={null}
import { useBasic } from '@basictech/react'

function App() {
  const { db } = useBasic()

  // Use .put() to upsert items - requires id in data
  const upsertItem = async () => {
    const item = await db.collection('tablename').put({ 
      id: 'specific-id-123', 
      name: 'updated name',
      completed: true 
    })
    console.log("Upserted item: ", item)
  }

  return (
    <>
      <button onClick={upsertItem}>Upsert Item</button>
    </>
  )
}
```

### Update item

```tsx App.tsx theme={null}
import { useBasic } from '@basictech/react'

function App() {
  const { db } = useBasic()

  // Use .update() to partially update items
  // Only the fields you provide will be changed
  const updateItem = async () => {
    const updated = await db.collection('tablename').update('ID_OF_ITEM', { 
      name: 'super cute' 
    })
    if (updated) {
      console.log("Successfully updated item: ", updated)
    } else {
      console.log("Item not found")
    }
  }

  return (
    <>
      <button onClick={updateItem}>Update Item</button>
    </>
  )
}
```

### Delete item

```tsx App.tsx theme={null}
import { useBasic } from '@basictech/react' 

function App() {
  const { db } = useBasic()

  // Use .delete() to delete items by ID
  const deleteItem = async () => {
    const deleted = await db.collection('tablename').delete('ID_OF_ITEM')
    if (deleted) {
      console.log("Successfully deleted item")
    } else {
      console.log("Item not found")
    }
  }

  return (
    <>
      <button onClick={deleteItem}>Delete Item</button>
    </>
  )
}
```

### Filter items

```tsx App.tsx theme={null}
import { useBasic } from '@basictech/react'
import { useState } from 'react'

function App() {
  const { db } = useBasic()
  const [completedItems, setCompletedItems] = useState([])

  // Use .filter() to filter items client-side
  const getCompletedItems = async () => {
    const items = await db.collection('todos').filter(
      (item) => item.completed === true
    )
    setCompletedItems(items)
    console.log("Completed items: ", items)
  }

  return (
    <>
      <button onClick={getCompletedItems}>Get Completed</button>
    </>
  )
}
```

***

# TypeScript Support

The `collection` method supports generics for type-safe database operations:

```tsx App.tsx theme={null}
import { useBasic } from '@basictech/react'

// Define your item type
type Todo = {
  id: string
  title: string
  completed: boolean
  createdAt: string
}

function App() {
  const { db } = useBasic()

  // Type-safe collection access
  const todos = db.collection<Todo>('todos')

  const addTodo = async () => {
    // TypeScript knows the shape of your data
    const newTodo = await todos.add({
      title: 'Learn Basic',
      completed: false,
      createdAt: new Date().toISOString()
    })
    console.log(newTodo.id) // TypeScript knows this exists
  }

  return <button onClick={addTodo}>Add Todo</button>
}
```
