Page updated Nov 15, 2023

Optimistic UI

The GraphQL API category can be used with TanStack Query to implement optimistic UI, allowing CRUD operations to be rendered immediately on the UI before the request roundtrip has completed. Using the GraphQL API with TanStack additionally makes it easy to render loading and error states, and allows you to rollback changes on the UI when API calls are unsuccessful.

In the following examples we'll create a list view that optimistically renders newly created items, and a detail view that optimistically renders updates and deletes.

For more details on TanStack Query, including requirements, supported browsers, and advanced usage, see the TanStack Query documentation. For complete guidance on how to implement optimistic updates with TanStack Query, see the TanStack Query Optimistic UI Documentation. For more on the Amplify GraphQL API, see the API documentation.

To get started, run the following command in an existing Amplify project with a React frontend:

# Install TanStack Query npm i @tanstack/react-query # Select default configuration amplify add api
1# Install TanStack Query
2npm i @tanstack/react-query
3
4# Select default configuration
5amplify add api

When prompted, use the following schema:

type RealEstateProperty @model @auth(rules: [{ allow: public }]) { id: ID! name: String! address: String }
1type RealEstateProperty @model @auth(rules: [{ allow: public }]) {
2 id: ID!
3 name: String!
4 address: String
5}

The schema file can also be found under amplify/backend/api/[name of project]/schema.graphql. Save the schema and run amplify push to deploy the changes. For the purposes of this guide, we'll build a Real Estate Property listing application.

Next, at the root of your project, add the required TanStack Query imports, and create a client:

import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; // Create a client const queryClient = new QueryClient()
1import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
2import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
3
4// Create a client
5const queryClient = new QueryClient()

Next, wrap your app in the client provider:

<QueryClientProvider client={queryClient}> <App /> <ReactQueryDevtools initialIsOpen={false} /> </QueryClientProvider>
1<QueryClientProvider client={queryClient}>
2 <App />
3 <ReactQueryDevtools initialIsOpen={false} />
4</QueryClientProvider>

TanStack Query Devtools are not required, but are a useful resource for debugging and understanding how TanStack works under the hood. By default, React Query Devtools are only included in bundles when process.env.NODE_ENV === 'development', meaning that no additional configuration is required to exclude them from a production build. For more information on the TanStack Query Devtools, visit the TanStack Query Devtools docs

For the complete working example, including required imports and React component state management, see the Complete Example below.

How to use TanStack Query query keys with the GraphQL API

TanStack Query manages query caching based on the query keys you specify. A query key must be an array. The array can contain a single string or multiple strings and nested objects. The query key must be serializable, and unique to the query's data.

When using TanStack to render optimistic UI with the GraphQL API, it is important to note that different query keys must be used depending on the API operation. When retrieving a list of items, a single string is used (e.g. queryKey: ["realEstateProperties"]). This query key is also used to optimistically render a newly created item. When updating or deleting an item, the query key must also include the unique identifier for the record being deleted or updated (e.g. queryKey: ["realEstateProperties", newRealEstateProperty.id]).

For more detailed information on query keys, see the TanStack Query documentation.

Optimistically rendering a list of records

To optimistically render a list of items returned from the GraphQL API, use the TanStack useQuery hook, passing in the GraphQL API query as the queryFn parameter. The following example creates a query to retrieve all records from the API. We'll use realEstateProperties as the query key, which will be the same key we use to optimistically render a newly created item.

const { data: realEstateProperties, isLoading, isSuccess, isError: isErrorQuery, } = useQuery({ queryKey: ["realEstateProperties"], queryFn: async () => { const response = await API.graphql< GraphQLQuery<ListRealEstatePropertiesQuery> >({ query: queries.listRealEstateProperties, }); const allRealEstateProperties = response?.data?.listRealEstateProperties?.items; if (!allRealEstateProperties) return null; return allRealEstateProperties; }, });
1const {
2 data: realEstateProperties,
3 isLoading,
4 isSuccess,
5 isError: isErrorQuery,
6} = useQuery({
7 queryKey: ["realEstateProperties"],
8 queryFn: async () => {
9 const response = await API.graphql<
10 GraphQLQuery<ListRealEstatePropertiesQuery>
11 >({
12 query: queries.listRealEstateProperties,
13 });
14
15 const allRealEstateProperties =
16 response?.data?.listRealEstateProperties?.items;
17
18 if (!allRealEstateProperties) return null;
19
20 return allRealEstateProperties;
21 },
22});

Optimistically rendering a newly created record

To optimistically render a newly created record returned from the GraphQL API, use the TanStack useMutation hook, passing in the GraphQL API mutation as the mutationFn parameter. We'll use the same query key used by the useQuery hook (realEstateProperties) as the query key to optimistically render a newly created item. We'll use the onMutate function to update the cache directly, as well as the onError function to rollback changes when a request fails.

const createMutation = useMutation({ mutationFn: async ( realEstatePropertyDetails: CreateRealEstatePropertyInput ) => { const response = await API.graphql< GraphQLQuery<CreateRealEstatePropertyMutation> >({ query: mutations.createRealEstateProperty, variables: { input: realEstatePropertyDetails }, }); const newRealEstateProperty = response?.data?.createRealEstateProperty; return newRealEstateProperty; }, // When mutate is called: onMutate: async (newRealEstateProperty) => { // Cancel any outgoing refetches // (so they don't overwrite our optimistic update) await queryClient.cancelQueries({ queryKey: ["realEstateProperties"] }); // Snapshot the previous value const previousRealEstateProperties = queryClient.getQueryData([ "realEstateProperties", ]); // Optimistically update to the new value if (previousRealEstateProperties) { queryClient.setQueryData(["realEstateProperties"], (old: any) => [ ...old, newRealEstateProperty, ]); } // Return a context object with the snapshotted value return { previousRealEstateProperties }; }, // If the mutation fails, // use the context returned from onMutate to rollback onError: (err, newRealEstateProperty, context) => { console.error("Error saving record:", err, newRealEstateProperty); if (context?.previousRealEstateProperties) { queryClient.setQueryData( ["realEstateProperties"], context.previousRealEstateProperties ); } }, // Always refetch after error or success: onSettled: () => { queryClient.invalidateQueries({ queryKey: ["realEstateProperties"] }); }, });
1const createMutation = useMutation({
2 mutationFn: async (
3 realEstatePropertyDetails: CreateRealEstatePropertyInput
4 ) => {
5 const response = await API.graphql<
6 GraphQLQuery<CreateRealEstatePropertyMutation>
7 >({
8 query: mutations.createRealEstateProperty,
9 variables: { input: realEstatePropertyDetails },
10 });
11
12 const newRealEstateProperty = response?.data?.createRealEstateProperty;
13 return newRealEstateProperty;
14 },
15 // When mutate is called:
16 onMutate: async (newRealEstateProperty) => {
17 // Cancel any outgoing refetches
18 // (so they don't overwrite our optimistic update)
19 await queryClient.cancelQueries({ queryKey: ["realEstateProperties"] });
20
21 // Snapshot the previous value
22 const previousRealEstateProperties = queryClient.getQueryData([
23 "realEstateProperties",
24 ]);
25
26 // Optimistically update to the new value
27 if (previousRealEstateProperties) {
28 queryClient.setQueryData(["realEstateProperties"], (old: any) => [
29 ...old,
30 newRealEstateProperty,
31 ]);
32 }
33
34 // Return a context object with the snapshotted value
35 return { previousRealEstateProperties };
36 },
37 // If the mutation fails,
38 // use the context returned from onMutate to rollback
39 onError: (err, newRealEstateProperty, context) => {
40 console.error("Error saving record:", err, newRealEstateProperty);
41 if (context?.previousRealEstateProperties) {
42 queryClient.setQueryData(
43 ["realEstateProperties"],
44 context.previousRealEstateProperties
45 );
46 }
47 },
48 // Always refetch after error or success:
49 onSettled: () => {
50 queryClient.invalidateQueries({ queryKey: ["realEstateProperties"] });
51 },
52});

Querying a single item with TanStack Query

To optimistically render updates on a single item, we'll first retrieve the item from the API. We'll use the useQuery hook, passing in the GraphQL API query as the queryFn parameter. For the query key, we'll use a combination of realEstateProperties and the record's unique identifier.

const { data: realEstateProperty, isLoading, isSuccess, isError: isErrorQuery, } = useQuery({ queryKey: ["realEstateProperties", currentRealEstatePropertyId], queryFn: async () => { const response = await API.graphql< GraphQLQuery<GetRealEstatePropertyQuery> >({ query: queries.getRealEstateProperty, variables: { id: currentRealEstatePropertyId }, }); return response.data?.getRealEstateProperty; }, });
1const {
2 data: realEstateProperty,
3 isLoading,
4 isSuccess,
5 isError: isErrorQuery,
6} = useQuery({
7 queryKey: ["realEstateProperties", currentRealEstatePropertyId],
8 queryFn: async () => {
9 const response = await API.graphql<
10 GraphQLQuery<GetRealEstatePropertyQuery>
11 >({
12 query: queries.getRealEstateProperty,
13 variables: { id: currentRealEstatePropertyId },
14 });
15
16 return response.data?.getRealEstateProperty;
17 },
18});

Optimistically render updates for a record

To optimistically render GraphQL API updates for a single record, use the TanStack useMutation hook, passing in the GraphQL API update mutation as the mutationFn parameter. We'll use the same query key combination used by the single record useQuery hook (realEstateProperties and the record's id) as the query key to optimistically render the updates. We'll use the onMutate function to update the cache directly, as well as the onError function to rollback changes when a request fails.

When directly interacting with the cache via the onMutate function, it should be noted that the newRealEstateProperty parameter only includes the fields that are being updated, until the final return from the GraphQL API returns all fields for the record. When calling setQueryData, include the previous values for all fields in addition to the newly updated fields to avoid only rendering optimistic values for updated fields on the UI.

const updateMutation = useMutation({ mutationFn: async ( realEstatePropertyDetails: UpdateRealEstatePropertyInput ) => { const response = await API.graphql< GraphQLQuery<UpdateRealEstatePropertyMutation> >({ query: mutations.updateRealEstateProperty, variables: { input: realEstatePropertyDetails }, }); return response?.data?.updateRealEstateProperty; }, // When mutate is called: onMutate: async (newRealEstateProperty) => { // Cancel any outgoing refetches // (so they don't overwrite our optimistic update) await queryClient.cancelQueries({ queryKey: ["realEstateProperties", newRealEstateProperty.id], }); await queryClient.cancelQueries({ queryKey: ["realEstateProperties"], }); // Snapshot the previous value const previousRealEstateProperty = queryClient.getQueryData([ "realEstateProperties", newRealEstateProperty.id, ]); // Optimistically update to the new value if (previousRealEstateProperty) { queryClient.setQueryData( ["realEstateProperties", newRealEstateProperty.id], /** * `newRealEstateProperty` will at first only include updated values for * the record. To avoid only rendering optimistic values for updated * fields on the UI, include the previous values for all fields: */ { ...previousRealEstateProperty, ...newRealEstateProperty } ); } // Return a context with the previous and new realEstateProperty return { previousRealEstateProperty, newRealEstateProperty }; }, // If the mutation fails, use the context we returned above onError: (err, newRealEstateProperty, context) => { console.error("Error updating record:", err, newRealEstateProperty); if (context?.previousRealEstateProperty) { queryClient.setQueryData( ["realEstateProperties", context.newRealEstateProperty.id], context.previousRealEstateProperty ); } }, // Always refetch after error or success: onSettled: (newRealEstateProperty) => { if (newRealEstateProperty) { queryClient.invalidateQueries({ queryKey: ["realEstateProperties", newRealEstateProperty.id], }); queryClient.invalidateQueries({ queryKey: ["realEstateProperties"], }); } }, });
1const updateMutation = useMutation({
2 mutationFn: async (
3 realEstatePropertyDetails: UpdateRealEstatePropertyInput
4 ) => {
5 const response = await API.graphql<
6 GraphQLQuery<UpdateRealEstatePropertyMutation>
7 >({
8 query: mutations.updateRealEstateProperty,
9 variables: { input: realEstatePropertyDetails },
10 });
11
12 return response?.data?.updateRealEstateProperty;
13 },
14 // When mutate is called:
15 onMutate: async (newRealEstateProperty) => {
16 // Cancel any outgoing refetches
17 // (so they don't overwrite our optimistic update)
18 await queryClient.cancelQueries({
19 queryKey: ["realEstateProperties", newRealEstateProperty.id],
20 });
21
22 await queryClient.cancelQueries({
23 queryKey: ["realEstateProperties"],
24 });
25
26 // Snapshot the previous value
27 const previousRealEstateProperty = queryClient.getQueryData([
28 "realEstateProperties",
29 newRealEstateProperty.id,
30 ]);
31
32 // Optimistically update to the new value
33 if (previousRealEstateProperty) {
34 queryClient.setQueryData(
35 ["realEstateProperties", newRealEstateProperty.id],
36 /**
37 * `newRealEstateProperty` will at first only include updated values for
38 * the record. To avoid only rendering optimistic values for updated
39 * fields on the UI, include the previous values for all fields:
40 */
41 { ...previousRealEstateProperty, ...newRealEstateProperty }
42 );
43 }
44
45 // Return a context with the previous and new realEstateProperty
46 return { previousRealEstateProperty, newRealEstateProperty };
47 },
48 // If the mutation fails, use the context we returned above
49 onError: (err, newRealEstateProperty, context) => {
50 console.error("Error updating record:", err, newRealEstateProperty);
51 if (context?.previousRealEstateProperty) {
52 queryClient.setQueryData(
53 ["realEstateProperties", context.newRealEstateProperty.id],
54 context.previousRealEstateProperty
55 );
56 }
57 },
58 // Always refetch after error or success:
59 onSettled: (newRealEstateProperty) => {
60 if (newRealEstateProperty) {
61 queryClient.invalidateQueries({
62 queryKey: ["realEstateProperties", newRealEstateProperty.id],
63 });
64 queryClient.invalidateQueries({
65 queryKey: ["realEstateProperties"],
66 });
67 }
68 },
69});

Optimistically render deleting a record

To optimistically render a GraphQL API delete of a single record, use the TanStack useMutation hook, passing in the GraphQL API delete mutation as the mutationFn parameter. We'll use the same query key combination used by the single record useQuery hook (realEstateProperties and the record's id) as the query key to optimistically render the updates. We'll use the onMutate function to update the cache directly, as well as the onError function to rollback changes when a delete fails.

const deleteMutation = useMutation({ mutationFn: async ( realEstatePropertyDetails: DeleteRealEstatePropertyInput ) => { const response = await API.graphql< GraphQLQuery<DeleteRealEstatePropertyMutation> >({ query: mutations.deleteRealEstateProperty, variables: { input: realEstatePropertyDetails }, }); return response?.data?.deleteRealEstateProperty; }, // When mutate is called: onMutate: async (newRealEstateProperty) => { // Cancel any outgoing refetches // (so they don't overwrite our optimistic update) await queryClient.cancelQueries({ queryKey: ["realEstateProperties", newRealEstateProperty.id], }); await queryClient.cancelQueries({ queryKey: ["realEstateProperties"], }); // Snapshot the previous value const previousRealEstateProperty = queryClient.getQueryData([ "realEstateProperties", newRealEstateProperty.id, ]); // Optimistically update to the new value if (previousRealEstateProperty) { queryClient.setQueryData( ["realEstateProperties", newRealEstateProperty.id], newRealEstateProperty ); } // Return a context with the previous and new realEstateProperty return { previousRealEstateProperty, newRealEstateProperty }; }, // If the mutation fails, use the context we returned above onError: (err, newRealEstateProperty, context) => { console.error("Error deleting record:", err, newRealEstateProperty); if (context?.previousRealEstateProperty) { queryClient.setQueryData( ["realEstateProperties", context.newRealEstateProperty.id], context.previousRealEstateProperty ); } }, // Always refetch after error or success: onSettled: (newRealEstateProperty) => { if (newRealEstateProperty) { queryClient.invalidateQueries({ queryKey: ["realEstateProperties", newRealEstateProperty.id], }); queryClient.invalidateQueries({ queryKey: ["realEstateProperties"], }); } }, });
1const deleteMutation = useMutation({
2 mutationFn: async (
3 realEstatePropertyDetails: DeleteRealEstatePropertyInput
4 ) => {
5 const response = await API.graphql<
6 GraphQLQuery<DeleteRealEstatePropertyMutation>
7 >({
8 query: mutations.deleteRealEstateProperty,
9 variables: { input: realEstatePropertyDetails },
10 });
11
12 return response?.data?.deleteRealEstateProperty;
13 },
14 // When mutate is called:
15 onMutate: async (newRealEstateProperty) => {
16 // Cancel any outgoing refetches
17 // (so they don't overwrite our optimistic update)
18 await queryClient.cancelQueries({
19 queryKey: ["realEstateProperties", newRealEstateProperty.id],
20 });
21
22 await queryClient.cancelQueries({
23 queryKey: ["realEstateProperties"],
24 });
25
26 // Snapshot the previous value
27 const previousRealEstateProperty = queryClient.getQueryData([
28 "realEstateProperties",
29 newRealEstateProperty.id,
30 ]);
31
32 // Optimistically update to the new value
33 if (previousRealEstateProperty) {
34 queryClient.setQueryData(
35 ["realEstateProperties", newRealEstateProperty.id],
36 newRealEstateProperty
37 );
38 }
39
40 // Return a context with the previous and new realEstateProperty
41 return { previousRealEstateProperty, newRealEstateProperty };
42 },
43 // If the mutation fails, use the context we returned above
44 onError: (err, newRealEstateProperty, context) => {
45 console.error("Error deleting record:", err, newRealEstateProperty);
46 if (context?.previousRealEstateProperty) {
47 queryClient.setQueryData(
48 ["realEstateProperties", context.newRealEstateProperty.id],
49 context.previousRealEstateProperty
50 );
51 }
52 },
53 // Always refetch after error or success:
54 onSettled: (newRealEstateProperty) => {
55 if (newRealEstateProperty) {
56 queryClient.invalidateQueries({
57 queryKey: ["realEstateProperties", newRealEstateProperty.id],
58 });
59 queryClient.invalidateQueries({
60 queryKey: ["realEstateProperties"],
61 });
62 }
63 },
64});

Loading and error states for optimistically rendered data

Both useQuery and useMutation return isLoading and isError states that indicate the current state of the query or mutation. You can use these states to render loading and error indicators.

In addition to operation-specific loading states, TanStack Query provides a useIsFetching hook. For the purposes of this demo, we show a global loading indicator in the Complete Example when any queries are fetching (including in the background) in order to help visualize what TanStack is doing in the background:

function GlobalLoadingIndicator() { const isFetching = useIsFetching(); return isFetching ? <div style={styles.globalLoadingIndicator}></div> : null; }
1function GlobalLoadingIndicator() {
2 const isFetching = useIsFetching();
3 return isFetching ? <div style={styles.globalLoadingIndicator}></div> : null;
4}

For more details on advanced usage of TanStack Query hooks, see the TanStack documentation.

The following example demonstrates how to use the state returned by TanStack to render a loading indicator while a mutation is in progress, and an error message if the mutation fails. For additional examples, see the Complete Example below.

<> {updateMutation.isError && updateMutation.error instanceof Error ? ( <div>An error occurred: {updateMutation.error.message}</div> ) : null} {updateMutation.isSuccess ? ( <div>Real Estate Property updated!</div> ) : null} <button onClick={() => updateMutation.mutate({ id: realEstateProperty.id, address: `${Math.floor( 1000 + Math.random() * 9000 )} Main St`, }) } > Update Address </button> </>
1<>
2 {updateMutation.isError &&
3 updateMutation.error instanceof Error ? (
4 <div>An error occurred: {updateMutation.error.message}</div>
5 ) : null}
6
7 {updateMutation.isSuccess ? (
8 <div>Real Estate Property updated!</div>
9 ) : null}
10
11 <button
12 onClick={() =>
13 updateMutation.mutate({
14 id: realEstateProperty.id,
15 address: `${Math.floor(
16 1000 + Math.random() * 9000
17 )} Main St`,
18 })
19 }
20 >
21 Update Address
22 </button>
23</>

Complete example

// index.tsx: import React from "react"; import ReactDOM from "react-dom/client"; import "./index.css"; import App from "./App"; import { Amplify } from "aws-amplify"; import awsExports from "./aws-exports"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { ReactQueryDevtools } from "@tanstack/react-query-devtools"; import "@aws-amplify/ui-react/styles.css"; Amplify.configure(awsExports); // Create a client const queryClient = new QueryClient(); const root = ReactDOM.createRoot( document.getElementById("root") as HTMLElement ); // Provide the client to your App root.render( <React.StrictMode> <QueryClientProvider client={queryClient}> <App /> <ReactQueryDevtools initialIsOpen={false} /> </QueryClientProvider> </React.StrictMode> ); // App.tsx: import React, { useState } from "react"; import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query"; import { useIsFetching } from "@tanstack/react-query"; import { API } from "aws-amplify"; import * as mutations from "./graphql/mutations"; import * as queries from "./graphql/queries"; import { GraphQLQuery } from "@aws-amplify/api"; import { CreateRealEstatePropertyInput, CreateRealEstatePropertyMutation, DeleteRealEstatePropertyInput, DeleteRealEstatePropertyMutation, GetRealEstatePropertyQuery, ListRealEstatePropertiesQuery, RealEstateProperty, UpdateRealEstatePropertyInput, UpdateRealEstatePropertyMutation, } from "./API"; /** * https://www.tanstack.com/query/v4/docs/react/guides/background-fetching-indicators#displaying-global-background-fetching-loading-state * For the purposes of this demo, we show a global loading indicator when *any* * queries are fetching (including in the background) in order to help visualize * what TanStack is doing in the background. This example also displays * indicators for individual query and mutation loading states. */ function GlobalLoadingIndicator() { const isFetching = useIsFetching(); return isFetching ? <div style={styles.globalLoadingIndicator}></div> : null; } function App() { const [currentRealEstatePropertyId, setCurrentRealEstatePropertyId] = useState<string | null>(null); // Access the client const queryClient = useQueryClient(); // TanStack Query for listing all real estate properties: const { data: realEstateProperties, isLoading, isSuccess, isError: isErrorQuery, } = useQuery({ queryKey: ["realEstateProperties"], queryFn: async () => { const response = await API.graphql< GraphQLQuery<ListRealEstatePropertiesQuery> >({ query: queries.listRealEstateProperties, }); const allRealEstateProperties = response?.data?.listRealEstateProperties?.items; if (!allRealEstateProperties) return null; return allRealEstateProperties; }, }); // TanStack create mutation with optimistic updates const createMutation = useMutation({ mutationFn: async ( realEstatePropertyDetails: CreateRealEstatePropertyInput ) => { const response = await API.graphql< GraphQLQuery<CreateRealEstatePropertyMutation> >({ query: mutations.createRealEstateProperty, variables: { input: realEstatePropertyDetails }, }); const newRealEstateProperty = response?.data?.createRealEstateProperty; return newRealEstateProperty; }, // When mutate is called: onMutate: async (newRealEstateProperty) => { // Cancel any outgoing refetches // (so they don't overwrite our optimistic update) await queryClient.cancelQueries({ queryKey: ["realEstateProperties"] }); // Snapshot the previous value const previousRealEstateProperties = queryClient.getQueryData([ "realEstateProperties", ]); // Optimistically update to the new value if (previousRealEstateProperties) { queryClient.setQueryData(["realEstateProperties"], (old: any) => [ ...old, newRealEstateProperty, ]); } // Return a context object with the snapshotted value return { previousRealEstateProperties }; }, // If the mutation fails, // use the context returned from onMutate to rollback onError: (err, newRealEstateProperty, context) => { console.error("Error saving record:", err, newRealEstateProperty); if (context?.previousRealEstateProperties) { queryClient.setQueryData( ["realEstateProperties"], context.previousRealEstateProperties ); } }, // Always refetch after error or success: onSettled: () => { queryClient.invalidateQueries({ queryKey: ["realEstateProperties"] }); }, }); /** * Note: this example does not return to the list view on delete in order * to demonstrate the optimistic update. */ function RealEstatePropertyDetailView() { const { data: realEstateProperty, isLoading, isSuccess, isError: isErrorQuery, } = useQuery({ queryKey: ["realEstateProperties", currentRealEstatePropertyId], queryFn: async () => { const response = await API.graphql< GraphQLQuery<GetRealEstatePropertyQuery> >({ query: queries.getRealEstateProperty, variables: { id: currentRealEstatePropertyId }, }); return response.data?.getRealEstateProperty; }, }); // TanStack update mutation with optimistic updates const updateMutation = useMutation({ mutationFn: async ( realEstatePropertyDetails: UpdateRealEstatePropertyInput ) => { const response = await API.graphql< GraphQLQuery<UpdateRealEstatePropertyMutation> >({ query: mutations.updateRealEstateProperty, variables: { input: realEstatePropertyDetails }, }); return response?.data?.updateRealEstateProperty; }, // When mutate is called: onMutate: async (newRealEstateProperty) => { // Cancel any outgoing refetches // (so they don't overwrite our optimistic update) await queryClient.cancelQueries({ queryKey: ["realEstateProperties", newRealEstateProperty.id], }); await queryClient.cancelQueries({ queryKey: ["realEstateProperties"], }); // Snapshot the previous value const previousRealEstateProperty = queryClient.getQueryData([ "realEstateProperties", newRealEstateProperty.id, ]); // Optimistically update to the new value if (previousRealEstateProperty) { queryClient.setQueryData( ["realEstateProperties", newRealEstateProperty.id], /** * `newRealEstateProperty` will at first only include updated values for * the record. To avoid only rendering optimistic values for updated * fields on the UI, include the previous values for all fields: */ { ...previousRealEstateProperty, ...newRealEstateProperty } ); } // Return a context with the previous and new realEstateProperty return { previousRealEstateProperty, newRealEstateProperty }; }, // If the mutation fails, use the context we returned above onError: (err, newRealEstateProperty, context) => { console.error("Error updating record:", err, newRealEstateProperty); if (context?.previousRealEstateProperty) { queryClient.setQueryData( ["realEstateProperties", context.newRealEstateProperty.id], context.previousRealEstateProperty ); } }, // Always refetch after error or success: onSettled: (newRealEstateProperty) => { if (newRealEstateProperty) { queryClient.invalidateQueries({ queryKey: ["realEstateProperties", newRealEstateProperty.id], }); queryClient.invalidateQueries({ queryKey: ["realEstateProperties"], }); } }, }); // TanStack delete mutation with optimistic updates const deleteMutation = useMutation({ mutationFn: async ( realEstatePropertyDetails: DeleteRealEstatePropertyInput ) => { const response = await API.graphql< GraphQLQuery<DeleteRealEstatePropertyMutation> >({ query: mutations.deleteRealEstateProperty, variables: { input: realEstatePropertyDetails }, }); return response?.data?.deleteRealEstateProperty; }, // When mutate is called: onMutate: async (newRealEstateProperty) => { // Cancel any outgoing refetches // (so they don't overwrite our optimistic update) await queryClient.cancelQueries({ queryKey: ["realEstateProperties", newRealEstateProperty.id], }); await queryClient.cancelQueries({ queryKey: ["realEstateProperties"], }); // Snapshot the previous value const previousRealEstateProperty = queryClient.getQueryData([ "realEstateProperties", newRealEstateProperty.id, ]); // Optimistically update to the new value if (previousRealEstateProperty) { queryClient.setQueryData( ["realEstateProperties", newRealEstateProperty.id], newRealEstateProperty ); } // Return a context with the previous and new realEstateProperty return { previousRealEstateProperty, newRealEstateProperty }; }, // If the mutation fails, use the context we returned above onError: (err, newRealEstateProperty, context) => { console.error("Error deleting record:", err, newRealEstateProperty); if (context?.previousRealEstateProperty) { queryClient.setQueryData( ["realEstateProperties", context.newRealEstateProperty.id], context.previousRealEstateProperty ); } }, // Always refetch after error or success: onSettled: (newRealEstateProperty) => { if (newRealEstateProperty) { queryClient.invalidateQueries({ queryKey: ["realEstateProperties", newRealEstateProperty.id], }); queryClient.invalidateQueries({ queryKey: ["realEstateProperties"], }); } }, }); return ( <div style={styles.detailViewContainer}> <h2>Real Estate Property Detail View</h2> {isErrorQuery && <div>{"Problem loading Real Estate Property"}</div>} {isLoading && ( <div style={styles.loadingIndicator}> {"Loading Real Estate Property..."} </div> )} {isSuccess && ( <div> <p>{`Name: ${realEstateProperty?.name}`}</p> <p>{`Address: ${realEstateProperty?.address}`}</p> </div> )} {realEstateProperty && ( <div> <div> {updateMutation.isLoading ? ( "Updating Real Estate Property..." ) : ( <> {updateMutation.isError && updateMutation.error instanceof Error ? ( <div>An error occurred: {updateMutation.error.message}</div> ) : null} {updateMutation.isSuccess ? ( <div>Real Estate Property updated!</div> ) : null} <button onClick={() => updateMutation.mutate({ id: realEstateProperty.id, name: `Updated Home ${Date.now()}`, }) } > Update Name </button> <button onClick={() => updateMutation.mutate({ id: realEstateProperty.id, address: `${Math.floor( 1000 + Math.random() * 9000 )} Main St`, }) } > Update Address </button> </> )} </div> <div> {deleteMutation.isLoading ? ( "Deleting Real Estate Property..." ) : ( <> {deleteMutation.isError && deleteMutation.error instanceof Error ? ( <div>An error occurred: {deleteMutation.error.message}</div> ) : null} {deleteMutation.isSuccess ? ( <div>Real Estate Property deleted!</div> ) : null} <button onClick={() => deleteMutation.mutate({ id: realEstateProperty.id, }) } > Delete </button> </> )} </div> </div> )} <button onClick={() => setCurrentRealEstatePropertyId(null)}> Back </button> </div> ); } return ( <div> {!currentRealEstatePropertyId && ( <div style={styles.appContainer}> <h1>Real Estate Properties:</h1> <div> {createMutation.isLoading ? ( "Adding Real Estate Property..." ) : ( <> {createMutation.isError && createMutation.error instanceof Error ? ( <div>An error occurred: {createMutation.error.message}</div> ) : null} {createMutation.isSuccess ? ( <div>Real Estate Property added!</div> ) : null} <button onClick={() => { createMutation.mutate({ name: `New Home ${Date.now()}`, address: `${Math.floor( 1000 + Math.random() * 9000 )} Main St`, }); }} > Add RealEstateProperty </button> </> )} </div> <ul style={styles.propertiesList}> {isLoading && ( <div style={styles.loadingIndicator}> {"Loading Real Estate Properties..."} </div> )} {isErrorQuery && ( <div>{"Problem loading Real Estate Properties"}</div> )} {isSuccess && realEstateProperties?.map((realEstateProperty, idx) => { if (!realEstateProperty) return null; return ( <li style={styles.listItem} key={`${idx}-${realEstateProperty.id}`} > <p>{realEstateProperty.name}</p> <button style={styles.detailViewButton} onClick={() => setCurrentRealEstatePropertyId(realEstateProperty.id) } > Detail View </button> </li> ); })} </ul> </div> )} {currentRealEstatePropertyId && <RealEstatePropertyDetailView />} <GlobalLoadingIndicator /> </div> ); } export default App; const styles: any = { appContainer: { display: "flex", flexDirection: "column", alignItems: "center", }, detailViewButton: { marginLeft: "1rem" }, detailViewContainer: { border: "1px solid black", padding: "3rem" }, globalLoadingIndicator: { position: "fixed", top: 0, left: 0, width: "100%", height: "100%", border: "4px solid blue", pointerEvents: "none", }, listItem: { display: "flex", justifyContent: "space-between", border: "1px dotted grey", padding: ".5rem", margin: ".1rem", }, loadingIndicator: { border: "1px solid black", padding: "1rem", margin: "1rem", }, propertiesList: { display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "start", width: "50%", border: "1px solid black", padding: "1rem", listStyleType: "none", }, };
1// index.tsx:
2import React from "react";
3import ReactDOM from "react-dom/client";
4import "./index.css";
5import App from "./App";
6import { Amplify } from "aws-amplify";
7import awsExports from "./aws-exports";
8import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
9import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
10import "@aws-amplify/ui-react/styles.css";
11
12Amplify.configure(awsExports);
13
14// Create a client
15const queryClient = new QueryClient();
16
17const root = ReactDOM.createRoot(
18 document.getElementById("root") as HTMLElement
19);
20
21// Provide the client to your App
22root.render(
23 <React.StrictMode>
24 <QueryClientProvider client={queryClient}>
25 <App />
26 <ReactQueryDevtools initialIsOpen={false} />
27 </QueryClientProvider>
28 </React.StrictMode>
29);
30
31// App.tsx:
32import React, { useState } from "react";
33import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
34import { useIsFetching } from "@tanstack/react-query";
35import { API } from "aws-amplify";
36import * as mutations from "./graphql/mutations";
37import * as queries from "./graphql/queries";
38import { GraphQLQuery } from "@aws-amplify/api";
39import {
40 CreateRealEstatePropertyInput,
41 CreateRealEstatePropertyMutation,
42 DeleteRealEstatePropertyInput,
43 DeleteRealEstatePropertyMutation,
44 GetRealEstatePropertyQuery,
45 ListRealEstatePropertiesQuery,
46 RealEstateProperty,
47 UpdateRealEstatePropertyInput,
48 UpdateRealEstatePropertyMutation,
49} from "./API";
50
51/**
52 * https://www.tanstack.com/query/v4/docs/react/guides/background-fetching-indicators#displaying-global-background-fetching-loading-state
53 * For the purposes of this demo, we show a global loading indicator when *any*
54 * queries are fetching (including in the background) in order to help visualize
55 * what TanStack is doing in the background. This example also displays
56 * indicators for individual query and mutation loading states.
57 */
58function GlobalLoadingIndicator() {
59 const isFetching = useIsFetching();
60
61 return isFetching ? <div style={styles.globalLoadingIndicator}></div> : null;
62}
63
64function App() {
65 const [currentRealEstatePropertyId, setCurrentRealEstatePropertyId] =
66 useState<string | null>(null);
67
68 // Access the client
69 const queryClient = useQueryClient();
70
71 // TanStack Query for listing all real estate properties:
72 const {
73 data: realEstateProperties,
74 isLoading,
75 isSuccess,
76 isError: isErrorQuery,
77 } = useQuery({
78 queryKey: ["realEstateProperties"],
79 queryFn: async () => {
80 const response = await API.graphql<
81 GraphQLQuery<ListRealEstatePropertiesQuery>
82 >({
83 query: queries.listRealEstateProperties,
84 });
85
86 const allRealEstateProperties =
87 response?.data?.listRealEstateProperties?.items;
88
89 if (!allRealEstateProperties) return null;
90
91 return allRealEstateProperties;
92 },
93 });
94
95 // TanStack create mutation with optimistic updates
96 const createMutation = useMutation({
97 mutationFn: async (
98 realEstatePropertyDetails: CreateRealEstatePropertyInput
99 ) => {
100 const response = await API.graphql<
101 GraphQLQuery<CreateRealEstatePropertyMutation>
102 >({
103 query: mutations.createRealEstateProperty,
104 variables: { input: realEstatePropertyDetails },
105 });
106
107 const newRealEstateProperty = response?.data?.createRealEstateProperty;
108 return newRealEstateProperty;
109 },
110 // When mutate is called:
111 onMutate: async (newRealEstateProperty) => {
112 // Cancel any outgoing refetches
113 // (so they don't overwrite our optimistic update)
114 await queryClient.cancelQueries({ queryKey: ["realEstateProperties"] });
115
116 // Snapshot the previous value
117 const previousRealEstateProperties = queryClient.getQueryData([
118 "realEstateProperties",
119 ]);
120
121 // Optimistically update to the new value
122 if (previousRealEstateProperties) {
123 queryClient.setQueryData(["realEstateProperties"], (old: any) => [
124 ...old,
125 newRealEstateProperty,
126 ]);
127 }
128
129 // Return a context object with the snapshotted value
130 return { previousRealEstateProperties };
131 },
132 // If the mutation fails,
133 // use the context returned from onMutate to rollback
134 onError: (err, newRealEstateProperty, context) => {
135 console.error("Error saving record:", err, newRealEstateProperty);
136 if (context?.previousRealEstateProperties) {
137 queryClient.setQueryData(
138 ["realEstateProperties"],
139 context.previousRealEstateProperties
140 );
141 }
142 },
143 // Always refetch after error or success:
144 onSettled: () => {
145 queryClient.invalidateQueries({ queryKey: ["realEstateProperties"] });
146 },
147 });
148
149 /**
150 * Note: this example does not return to the list view on delete in order
151 * to demonstrate the optimistic update.
152 */
153 function RealEstatePropertyDetailView() {
154 const {
155 data: realEstateProperty,
156 isLoading,
157 isSuccess,
158 isError: isErrorQuery,
159 } = useQuery({
160 queryKey: ["realEstateProperties", currentRealEstatePropertyId],
161 queryFn: async () => {
162 const response = await API.graphql<
163 GraphQLQuery<GetRealEstatePropertyQuery>
164 >({
165 query: queries.getRealEstateProperty,
166 variables: { id: currentRealEstatePropertyId },
167 });
168
169 return response.data?.getRealEstateProperty;
170 },
171 });
172
173 // TanStack update mutation with optimistic updates
174 const updateMutation = useMutation({
175 mutationFn: async (
176 realEstatePropertyDetails: UpdateRealEstatePropertyInput
177 ) => {
178 const response = await API.graphql<
179 GraphQLQuery<UpdateRealEstatePropertyMutation>
180 >({
181 query: mutations.updateRealEstateProperty,
182 variables: { input: realEstatePropertyDetails },
183 });
184
185 return response?.data?.updateRealEstateProperty;
186 },
187 // When mutate is called:
188 onMutate: async (newRealEstateProperty) => {
189 // Cancel any outgoing refetches
190 // (so they don't overwrite our optimistic update)
191 await queryClient.cancelQueries({
192 queryKey: ["realEstateProperties", newRealEstateProperty.id],
193 });
194
195 await queryClient.cancelQueries({
196 queryKey: ["realEstateProperties"],
197 });
198
199 // Snapshot the previous value
200 const previousRealEstateProperty = queryClient.getQueryData([
201 "realEstateProperties",
202 newRealEstateProperty.id,
203 ]);
204
205 // Optimistically update to the new value
206 if (previousRealEstateProperty) {
207 queryClient.setQueryData(
208 ["realEstateProperties", newRealEstateProperty.id],
209 /**
210 * `newRealEstateProperty` will at first only include updated values for
211 * the record. To avoid only rendering optimistic values for updated
212 * fields on the UI, include the previous values for all fields:
213 */
214 { ...previousRealEstateProperty, ...newRealEstateProperty }
215 );
216 }
217
218 // Return a context with the previous and new realEstateProperty
219 return { previousRealEstateProperty, newRealEstateProperty };
220 },
221 // If the mutation fails, use the context we returned above
222 onError: (err, newRealEstateProperty, context) => {
223 console.error("Error updating record:", err, newRealEstateProperty);
224 if (context?.previousRealEstateProperty) {
225 queryClient.setQueryData(
226 ["realEstateProperties", context.newRealEstateProperty.id],
227 context.previousRealEstateProperty
228 );
229 }
230 },
231 // Always refetch after error or success:
232 onSettled: (newRealEstateProperty) => {
233 if (newRealEstateProperty) {
234 queryClient.invalidateQueries({
235 queryKey: ["realEstateProperties", newRealEstateProperty.id],
236 });
237 queryClient.invalidateQueries({
238 queryKey: ["realEstateProperties"],
239 });
240 }
241 },
242 });
243
244 // TanStack delete mutation with optimistic updates
245 const deleteMutation = useMutation({
246 mutationFn: async (
247 realEstatePropertyDetails: DeleteRealEstatePropertyInput
248 ) => {
249 const response = await API.graphql<
250 GraphQLQuery<DeleteRealEstatePropertyMutation>
251 >({
252 query: mutations.deleteRealEstateProperty,
253 variables: { input: realEstatePropertyDetails },
254 });
255
256 return response?.data?.deleteRealEstateProperty;
257 },
258 // When mutate is called:
259 onMutate: async (newRealEstateProperty) => {
260 // Cancel any outgoing refetches
261 // (so they don't overwrite our optimistic update)
262 await queryClient.cancelQueries({
263 queryKey: ["realEstateProperties", newRealEstateProperty.id],
264 });
265
266 await queryClient.cancelQueries({
267 queryKey: ["realEstateProperties"],
268 });
269
270 // Snapshot the previous value
271 const previousRealEstateProperty = queryClient.getQueryData([
272 "realEstateProperties",
273 newRealEstateProperty.id,
274 ]);
275
276 // Optimistically update to the new value
277 if (previousRealEstateProperty) {
278 queryClient.setQueryData(
279 ["realEstateProperties", newRealEstateProperty.id],
280 newRealEstateProperty
281 );
282 }
283
284 // Return a context with the previous and new realEstateProperty
285 return { previousRealEstateProperty, newRealEstateProperty };
286 },
287 // If the mutation fails, use the context we returned above
288 onError: (err, newRealEstateProperty, context) => {
289 console.error("Error deleting record:", err, newRealEstateProperty);
290 if (context?.previousRealEstateProperty) {
291 queryClient.setQueryData(
292 ["realEstateProperties", context.newRealEstateProperty.id],
293 context.previousRealEstateProperty
294 );
295 }
296 },
297 // Always refetch after error or success:
298 onSettled: (newRealEstateProperty) => {
299 if (newRealEstateProperty) {
300 queryClient.invalidateQueries({
301 queryKey: ["realEstateProperties", newRealEstateProperty.id],
302 });
303 queryClient.invalidateQueries({
304 queryKey: ["realEstateProperties"],
305 });
306 }
307 },
308 });
309
310 return (
311 <div style={styles.detailViewContainer}>
312 <h2>Real Estate Property Detail View</h2>
313 {isErrorQuery && <div>{"Problem loading Real Estate Property"}</div>}
314 {isLoading && (
315 <div style={styles.loadingIndicator}>
316 {"Loading Real Estate Property..."}
317 </div>
318 )}
319 {isSuccess && (
320 <div>
321 <p>{`Name: ${realEstateProperty?.name}`}</p>
322 <p>{`Address: ${realEstateProperty?.address}`}</p>
323 </div>
324 )}
325 {realEstateProperty && (
326 <div>
327 <div>
328 {updateMutation.isLoading ? (
329 "Updating Real Estate Property..."
330 ) : (
331 <>
332 {updateMutation.isError &&
333 updateMutation.error instanceof Error ? (
334 <div>An error occurred: {updateMutation.error.message}</div>
335 ) : null}
336
337 {updateMutation.isSuccess ? (
338 <div>Real Estate Property updated!</div>
339 ) : null}
340
341 <button
342 onClick={() =>
343 updateMutation.mutate({
344 id: realEstateProperty.id,
345 name: `Updated Home ${Date.now()}`,
346 })
347 }
348 >
349 Update Name
350 </button>
351 <button
352 onClick={() =>
353 updateMutation.mutate({
354 id: realEstateProperty.id,
355 address: `${Math.floor(
356 1000 + Math.random() * 9000
357 )} Main St`,
358 })
359 }
360 >
361 Update Address
362 </button>
363 </>
364 )}
365 </div>
366
367 <div>
368 {deleteMutation.isLoading ? (
369 "Deleting Real Estate Property..."
370 ) : (
371 <>
372 {deleteMutation.isError &&
373 deleteMutation.error instanceof Error ? (
374 <div>An error occurred: {deleteMutation.error.message}</div>
375 ) : null}
376
377 {deleteMutation.isSuccess ? (
378 <div>Real Estate Property deleted!</div>
379 ) : null}
380
381 <button
382 onClick={() =>
383 deleteMutation.mutate({
384 id: realEstateProperty.id,
385 })
386 }
387 >
388 Delete
389 </button>
390 </>
391 )}
392 </div>
393 </div>
394 )}
395 <button onClick={() => setCurrentRealEstatePropertyId(null)}>
396 Back
397 </button>
398 </div>
399 );
400 }
401
402 return (
403 <div>
404 {!currentRealEstatePropertyId && (
405 <div style={styles.appContainer}>
406 <h1>Real Estate Properties:</h1>
407 <div>
408 {createMutation.isLoading ? (
409 "Adding Real Estate Property..."
410 ) : (
411 <>
412 {createMutation.isError &&
413 createMutation.error instanceof Error ? (
414 <div>An error occurred: {createMutation.error.message}</div>
415 ) : null}
416
417 {createMutation.isSuccess ? (
418 <div>Real Estate Property added!</div>
419 ) : null}
420
421 <button
422 onClick={() => {
423 createMutation.mutate({
424 name: `New Home ${Date.now()}`,
425 address: `${Math.floor(
426 1000 + Math.random() * 9000
427 )} Main St`,
428 });
429 }}
430 >
431 Add RealEstateProperty
432 </button>
433 </>
434 )}
435 </div>
436 <ul style={styles.propertiesList}>
437 {isLoading && (
438 <div style={styles.loadingIndicator}>
439 {"Loading Real Estate Properties..."}
440 </div>
441 )}
442 {isErrorQuery && (
443 <div>{"Problem loading Real Estate Properties"}</div>
444 )}
445 {isSuccess &&
446 realEstateProperties?.map((realEstateProperty, idx) => {
447 if (!realEstateProperty) return null;
448 return (
449 <li
450 style={styles.listItem}
451 key={`${idx}-${realEstateProperty.id}`}
452 >
453 <p>{realEstateProperty.name}</p>
454 <button
455 style={styles.detailViewButton}
456 onClick={() =>
457 setCurrentRealEstatePropertyId(realEstateProperty.id)
458 }
459 >
460 Detail View
461 </button>
462 </li>
463 );
464 })}
465 </ul>
466 </div>
467 )}
468 {currentRealEstatePropertyId && <RealEstatePropertyDetailView />}
469 <GlobalLoadingIndicator />
470 </div>
471 );
472}
473
474export default App;
475
476const styles: any = {
477 appContainer: {
478 display: "flex",
479 flexDirection: "column",
480 alignItems: "center",
481 },
482 detailViewButton: { marginLeft: "1rem" },
483 detailViewContainer: { border: "1px solid black", padding: "3rem" },
484 globalLoadingIndicator: {
485 position: "fixed",
486 top: 0,
487 left: 0,
488 width: "100%",
489 height: "100%",
490 border: "4px solid blue",
491 pointerEvents: "none",
492 },
493 listItem: {
494 display: "flex",
495 justifyContent: "space-between",
496 border: "1px dotted grey",
497 padding: ".5rem",
498 margin: ".1rem",
499 },
500 loadingIndicator: {
501 border: "1px solid black",
502 padding: "1rem",
503 margin: "1rem",
504 },
505 propertiesList: {
506 display: "flex",
507 flexDirection: "column",
508 alignItems: "center",
509 justifyContent: "start",
510 width: "50%",
511 border: "1px solid black",
512 padding: "1rem",
513 listStyleType: "none",
514 },
515};