# Usage

### Docs moved to <https://react-firebase-js.com/docs/react-firestore-database/getting-started>

### Components

* FirestoreProvider
* FirestoreCollection
* FirestoreDocument
* FirestoreMutation
* FirestoreBatchedWrite

### Firestore Provider

Place a `FirestoreProvider` component at the top level of your app.&#x20;

```javascript
import { FirestoreProvider } from '@react-firebase/firestore'
// Before
const App = () => {
    return <div>
        This is my app
    </div>
}

// After
const App = () => {
    return (
        <FirestoreProvider {...config} firebase={firebase}>
            <div>
                This is my app
            </div>
        </FirestoreProvider>
    )
}
```

If you need to authenticate to access your data, check out [`@react-firebase/auth`](/rf/react-firebase-auth.md)

### Firestore Collection Example

```jsx
<FirestoreCollection path="/user_bookmarks/" limit={1}>
  {d => {
    return d.isLoading ? "Loading" : <pre>{d.value}</pre>;
  }}
</FirestoreCollection>
```

### Firestore Document Example

```jsx
<FirestoreDocument path="/user_bookmarks/G_K_1svqs">
  {d => {
    return d.isLoading ? "Loading" : <pre>{d.value}</pre>;
  }}
</FirestoreDocument>;
```

###

### Firestore Mutation

The `FirestoreMutation` allows you to render components that run Firebase mutations (update, set, add).

A `setMutation` function that returns a promise is provided to the children function.

FirebaseDatabaseMutation needs 3 props :&#x20;

* **path**: `string`
* **operation**: `"update" | "set" | "add"`&#x20;
* **children:**&#x20;

  | <p>(<br>  {<br>    runMutation: (value:any, options?:any) => Promise<{key?:string}><br>  }<br>) => ReactNode</p> |
  | ---------------------------------------------------------------------------------------------------------------- |

### Upsert (update or insert) data to Firestore example

```jsx
<FirestoreMutation type="set" path="/user_bookmarks/G_K_5onxu">
  {({ runMutation }) => {
    return (
      <div>
        <h2> Mutate state </h2>
        <button
          onClick={() => {
            runMutation({
              nowOnCli: Date.now(),
              nowOnServer: firebase.firestore.FieldValue.serverTimestamp()
            }).then(res => {
              console.log("Ran mutation ", res);
            });
          }}
        >
          Mutate Set
        </button>
      </div>
    );
  }}
</FirestoreMutation>
```

###

### Batched Writes

Schedule a mutation with `addMutationToBatch`, and commit your changes with `commit`.

```jsx
<FirestoreBatchedWrite>
  {({ addMutationToBatch, commit }) => {
    return (
      <div>
        <h2>Batched write</h2>
        <button
          onClick={() => {
            console.log("adding to batch");
            addMutationToBatch({
              path: `user_bookmarks/G_K_5onxu/`,
              value: { [`a-value-${Date.now()}`]: Date.now() },
              type: "update"
            });
          }}
        >
          Add to batch
        </button>
        <button
          onClick={() => {
            console.log("committing to batch");
            commit().then(() => {
              console.log("Committed");
            });
          }}
        >
          Commit batch
        </button>
      </div>
    );
  }}
</FirestoreBatchedWrite>;

```

### Complete Example

```jsx
import firebase from "firebase/app";
import "firebase/firestore";
import {
  FirestoreProvider,
  FirestoreCollection,
  FirestoreDocument
} from "react-firebase-firestore";
import ReactJson from "react-json-view";

const config = {
  apiKey: credentials.apiKey,
  authDomain: credentials.authDomain,
  databaseURL: credentials.databaseURL,
  projectId: credentials.projectId,
  storageBucket: credentials.storageBucket,
  messagingSenderId: credentials.messagingSenderId
};

const App = () => {
  return (
    <FirestoreProvider {...config} firebase={firebase}>
      <div>oh hai</div>
      <FirestoreDocument path="/user_bookmarks/G_K_1svqs">
        {d => {
          return d.loadingStatus === "ready" ? (
            <ReactJson src={d} />
          ) : (
            "Loading"
          );
        }}
      </FirestoreDocument>
      <div>
        <h4>oh hai again</h4>
        <FirestoreCollection path="/user_bookmarks/" limit={1}>
          {d => {
            return d.isLoading ? (
              "Loading"
            ) : (
              <ReactJson src={d} />
            );
          }}
        </FirestoreCollection>
        <FirestoreBatchedWrite>
        {({ addMutationToBatch, commit }) => {
          return (
            <div>
              {" "}
              <h2>Batched write</h2>{" "}
              <button
                onClick={() => {
                  console.log("adding to batch");
                  addMutationToBatch({
                    path: `user_bookmarks/G_K_5onxu/`,
                    value: { [`a-value-${Date.now()}`]: Date.now() },
                    type: "update"
                  });
                }}
              >
                Add to batch
              </button>
              <button
                onClick={() => {
                  console.log("committing to batch");
                  commit().then(() => {
                    console.log("Committed");
                  });
                }}
              >
                Commit batch
              </button>
            </div>
          );
        }}
      </FirestoreBatchedWrite>
      </div>
    </FirestoreProvider>
  );
};
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://react-firebase.gitbook.io/rf/react-firestore-database/usage.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
