Skip to content

Commit

Permalink
docs: Update data connect docs
Browse files Browse the repository at this point in the history
  • Loading branch information
Ehesp committed Dec 20, 2024
1 parent 242df90 commit 0d72bef
Show file tree
Hide file tree
Showing 7 changed files with 383 additions and 16 deletions.
29 changes: 25 additions & 4 deletions docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,12 +53,33 @@
"group": "Data Connect",
"pages": [
{
"href": "/react/hooks/data-connect/useConnectQuery",
"title": "useConnectQuery"
"title": "Getting Started",
"href": "/react/data-connect"
},
{
"href": "/react/hooks/data-connect/useConnectMutation",
"title": "useConnectMutation"
"title": "Querying",
"href": "/react/data-connect/querying"
},
{
"title": "Mutations",
"href": "/react/data-connect/mutations"
},
{
"title": "Server Side Rendering",
"href": "/react/data-connect/server-side-rendering"
},
{
"group": "Hooks",
"pages": [
{
"title": "useConnectQuery",
"href": "/react/data-connect/hooks/useConnectQuery"
},
{
"title": "useConnectMutation",
"href": "/react/data-connect/hooks/useConnectMutation"
}
]
}
]
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ title: useConnectMutation
---

`useConnectMutation` is a hook designed to simplify handling mutations (creating, updating, deleting) with Firebase Data Connect.
This hook integrates with [Firebase Data Connect](https://firebase.google.com/docs/data-connect), which uses GraphQL to interact with a PostgreSQL database (via Cloud SQL) for secure, scalable data operations.
The hook manages the mutation process and provides an easy-to-use interface to manage loading, success, and error states in your React application.

See [mutations](/react/data-connect/mutations) for more information.

## Features

- Simplifies mutation handling for <b>create</b>, <b>update</b>, and <b>delete</b> operations using Firebase Data Connect.
- Provides <b>type-safe</b> handling of mutations based on your Firebase Data Connect schema.
- Automatically manages <b>loading</b>, <b>success</b>, and <b>error</b> states for mutations.
- Automatically manages <b>pending</b>, <b>success</b>, and <b>error</b> states for mutations.
- Supports <b>optimistic updates</b> and <b>caching</b> to improve user experience and performance.

## Usage
Expand All @@ -23,21 +23,29 @@ function Component() {
const { mutate, isPending, isSuccess, isError, error } =
useConnectMutation(createMovieRef);

const handleSubmit = async (movieData) => {
try {
await mutate(movieData);
} catch (err) {
console.error("Failed to add movie:", err);
}
const handleFormSubmit = (e: React.FormEvent) => {
e.preventDefault();
const data = new FormData(e.target as HTMLFormElement);

mutate({
title: data.get("title") as string,
imageUrl: data.get("imageUrl") as string,
genre: data.get("genre") as string,
});
};

if (isPending) return <div>Adding movie...</div>;

if (isError) return <div>Error: {error.message}</div>;

return (
<div>
{isSuccess && <div>Movie added successfully!</div>}
<form onSubmit={(e) => handleSubmit(e.target)}>
<form onSubmit={handleFormSubmit}>
<input type="text" name="title" placeholder="Title" />
<input type="text" name="genre" placeholder="Genre" />
<input type="text" name="imageUrl" placeholder="Image URL" />

{/* Form fields for movie data */}
<button type="submit" disabled={isPending}>
Add Movie
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ title: useConnectQuery
---

`useConnectQuery` is a hook designed to simplify data fetching and state management with Firebase Data Connect.
This hook integrates with [Firebase Data Connect](https://firebase.google.com/docs/data-connect), which leverages GraphQL to interact with a PostgreSQL database (via Cloud SQL) for secure, scalable data operations.
The hook simplifies the process of querying data from Firebase Data Connect and provides an easy-to-use interface to manage loading, success, and error states in your React application.

See [querying](/react/data-connect/querying) for more information.

## Features

Expand Down
67 changes: 67 additions & 0 deletions docs/react/data-connect/index.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
---
title: Firebase Data Connect
---

Firebase Data Connect is a relational database service for mobile and web apps that lets you build and scale using a fully-managed PostgreSQL database powered by Cloud SQL. It provides secure schema, query and mutation management using GraphQL technology that integrates well with Firebase Authentication.

To get started, ensure you have setup your Firebase project and have the Data Connect setup in your project. To learn more,
follow the [Firebase Data Connect documentation](https://firebase.google.com/docs/data-connect/quickstart).

## Setup

Before using the Tanstack Query Firebase hooks for Data Connect, ensure you have configured your application using your chosen connector:

```ts
import { connectorConfig } from "../../dataconnect/default-connector";
import { initializeApp } from "firebase/app";
import { getDataConnect } from "firebase/data-connect";

// Initialize your Firebase app
initializeApp({ ... });

// Get the Data Connect instance
const dataConnect = getDataConnect(connectorConfig);

// Optionally, connect to the Data Connect Emulator
connectDataConnectEmulator(dataConnect, "localhost", 9399);
```

## Importing

The package exports are available via the `@tanstack-query-firebase/react` package under the `data-connect` namespace:

```ts
import { useConnectQuery } from "@tanstack-query-firebase/react/data-connect";
```

## Basic Usage

To use the Tanstack Query Firebase hooks for Data Connect, you can use the `useConnectQuery` hook to fetch data from the database:

```tsx
import { useConnectQuery } from "@tanstack-query-firebase/react";
import { listMoviesRef } from "../../dataconnect/default-connector";

function Component() {
const { data, isPending, isSuccess, isError, error } = useConnectQuery(
listMoviesRef()
);

if (isPending) return <div>Loading...</div>;

if (isError) return <div>Error: {error.message}</div>;

return <div>{isSuccess && <ul>{data.movies.map((movie) => <li key={movie.id}>{movie.title}</li>)}</ul>}</div>;
}
```

The hooks will automatically infer the data type from the connector and the query and automtically create a [query key](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for the query.

## Learning more

To learn more about the Data Connect hooks, check out the following pages:

- [Querying](/react/data-connect/querying)
- [Mutations](/react/data-connect/mutations)
- [Server Side Rendering](/react/data-connect/server-side-rendering)

85 changes: 85 additions & 0 deletions docs/react/data-connect/mutations.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
---
title: Mutations
description: Learn how to mutate data in Firebase Data Connect using the Tanstack Query Firebase hooks.
---

## Mutating Data

To mutate data in Firebase Data Connect, you can use the `useConnectMutation` hook.

```tsx
import { useConnectMutation } from "@tanstack-query-firebase/react";
import { createMovieRef } from "@dataconnect/default-connector";

function Component() {
const createMovie = useConnectMutation(
createMovieRef
);

return (
<button
disabled={createMovie.isPending}
onClick={() => {
createMovie.mutate({
title: 'John Wick',
genre: "Action",
imageUrl: "https://example.com/image.jpg",
});
}}
>
{createMovie.isPending ? "Creating..." : "Create Movie"}
</button>
);
}
```

## Invalidating Queries

The hook provides an additional [mutation option](https://tanstack.com/query/latest/docs/framework/react/reference/useMutation) called `invalidate`. This option accepts a list of query references which will be automatically invalidated when the mutation is successful.

```tsx
const createMovie = useConnectMutation(createMovieRef, {
invalidate: [getMovieRef],
});
```

### Implicit references

The above example provides a `getMovieRef` instance to the invalidate array. By default this will invalidate all queries that cached via the `getMovieRef` reference, for example the following query references will be invalidated:

```tsx
getMovieRef({ id: "1"});
getMovieRef({ id: "2"});
```

### Explicit references

You can also provide explicit references to the invalidate array, for example:

```tsx
const createMovie = useConnectMutation(createMovieRef, {
invalidate: [getMovieRef({ id: "1" })],
});
```

In this case only the query reference `getMovieRef({ id: "1" })` will be invalidated.

## Overriding the mutation key

### Metadata

Along with the data, the hook will also return the `ref`, `source`, and `fetchTime` metadata from the mutation.

```tsx
const createMovie = useConnectMutation(createMovieRef);

const data = await createMovie.mutateAsync({
title: 'John Wick',
genre: "Action",
imageUrl: "https://example.com/image.jpg",
});

console.log(data.ref);
console.log(data.source);
console.log(data.fetchTime);
```
80 changes: 80 additions & 0 deletions docs/react/data-connect/querying.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
---
title: Querying
description: Learn how to query data from Firebase Data Connect using the Tanstack Query Firebase hooks.
---

## Querying Data

To query data from Firebase Data Connect, you can use the `useConnectQuery` hook. This hook will automatically infer the data type from the connector and the query and automtically create a [query key](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for the query.

```tsx
import { useConnectQuery } from "@tanstack-query-firebase/react";
import { listMoviesRef } from "@dataconnect/default-connector";

function Component() {
const { data, isPending, isSuccess, isError, error } = useConnectQuery(
listMoviesRef()
);
}
```

### Query options

To leverage the full power of Tanstack Query, you can pass in query options to the `useConnectQuery` hook, for example to refetch the query on a interval:

```tsx
const { data, isPending, isSuccess, isError, error } = useConnectQuery(
listMoviesRef(),
{
refetchInterval: 1000,
}
);
```

The hook extends the [`useQuery`](https://tanstack.com/query/latest/docs/framework/react/reference/useQuery) hook, so you can learn more about the available options by reading the [Tanstack Query documentation](https://tanstack.com/query/latest/docs/framework/react/reference/useQuery).

### Overriding the query key

To override the query key, you can pass in a custom query key to the `useConnectQuery` hook:

```tsx
const { data, isPending, isSuccess, isError, error } = useConnectQuery(
getMovieRef({ id: "1" }),
{
queryKey: ["movies", "1"],
}
);
```

Note that overriding the query key could mean your query is no longer synchronized with mutation invalidations or server side rendering pre-fetching.

### Initial data

If your application has already fetched a data from Data Connect, you can instead pass the `QueryResult` instance to the hook. This will instead set the `initialData` option on the hook:

```tsx
// Elsewhere in your application
const movies = await executeQuery(listMoviesRef());

// ...

function Component(props: { movies: QueryResult<ListMoviesData, unknown> }) {
const { data, isPending, isSuccess, isError, error } = useConnectQuery(
props.movies
);
}
```

The hook will immediately have data available, and immediately refetch the data when the component is mounted. This behavior can be contolled by providing a `staleTime` value to the hook or Query Client.

### Metadata

Along with the data, the hook will also return the `ref`, `source`, and `fetchTime` metadata from the query.

```tsx
const { data } = useConnectQuery(listMoviesRef());

console.log(data?.ref);
console.log(data?.source);
console.log(data?.fetchTime);
```
Loading

0 comments on commit 0d72bef

Please sign in to comment.