usePouchDB

usePouchDB

  • Docs
  • API
  • Help
  • GitHub

›Basic Tutorial

Introduction

  • Quick Start
  • PouchDB and CouchDB

Basic Tutorial

  • 'Basic Tutorial: Intro'
  • Setup
  • Add the Provider
  • Add Todos
  • List all Todos
  • Update docs
  • Syncing
  • Testing
  • More

API

  • Provider
  • usePouch
  • useDoc
  • useAllDocs
  • useFind
  • useView

List all Todos

The <TodoList /> component is responsible for rendering the list of todos. Therefore, it needs to read data from the database. With useAllDocs we can! It loads all documents.

Our <Todo /> component takes the todo document as props and displays it.

// TodoList.js
import React from 'react'
import { useAllDocs } from 'use-pouchdb'
import Todo from './Todo'

export default function TodoList() {
  const { rows: todos, loading } = useAllDocs({
    include_docs: true, // Load all document bodies
  })

  return (
    <ul className="todo-list">
      {(todos && todos.length) || loading
        ? todos.map(todo => <Todo key={todo.key} todo={todo.doc} />)
        : 'No todos, yay!'}
    </ul>
  )
}

useAllDocs loads all documents sorted by their id. It also subscripts to changes in the database. When ever a new document will be added, or an existing one updated or deleted, useAllDocs will update its result. It can also only load a slice of all documents, but we don't need that here.

The rows field will contain an array of objects.

[
  {
    "key": "2020-05-25T21:42:17.275Z",
    "id": "2020-05-25T21:42:17.275Z",
    "value": {
      "rev": "1-1234567890"
    },
    "doc": {
      "_id": "2020-05-25T21:42:17.275Z",
      "_rev": "1-1234567890",
      "type": "todo",
      "text": "my first document!",
      "done": false
    }
  }
]

We use the option include_docs: true to load all documents in one go. Without it the doc field wouldn't exist.

Yes key and id are a little bit redundant. But the underlying db.allDocs and db.query (for useView) share most of their API.

Now to the <Todo /> component:

// Todo.js
import React from 'react'

export default function Todo({ todo }) {
  return (
    <li className="todo-item">
      <span className="todo-item__text">{todo.text}</span>
    </li>
  )
}

And add TodoList.js to App.js:

import React, { useState, useEffect } from 'react'
import './App.css'

import PouchDB from 'pouchdb-browser'
import { Provider } from 'use-pouchdb'

import AddTodo from './AddTodo'
import TodoList from './TodoList'

...
  return (
    <Provider pouchdb={db}>
      <div className="App">
        <TodoList />
        <AddTodo />
      </div>
    </Provider>
  )

And with that we have a Todo List! And, whenever you add a new Todo the list will update!

Next we will learn how to update a document!

← Add TodosUpdate docs →
usePouchDB
Docs
Getting StartedAPI Reference
Contact
BlogGitHubStar
Impressum
Copyright © 2023 Christopher Astfalk