Set up a GraphQL client (using something like graphql-request or apollo-client) and configure it to work with Remix.
Create a modular structure for GraphQL operations (queries, mutations, fragments) in a graphql directory.
Implement a way to handle optimistic updates. We can use the useMutation hook from a GraphQL client that supports optimistic UI, or we can manage optimistic state manually in the component and then use the mutation to update the server.
However, note that Remix has its own way of handling mutations via useFetcher or useSubmit. But we are using GraphQL, so we might want to use a GraphQL client that integrates with React's Suspense and also supports optimistic updates.
But Remix encourages using its own data loading and mutation methods. However, we can still use a GraphQL client and then use Remix's useFetcher to call our GraphQL mutations.
Alternatively, we can set up a route that handles GraphQL requests (like a single endpoint for all GraphQL operations) and then use useFetcher to call that endpoint.
However, for simplicity and to leverage Remix's built-in features, we might want to avoid a full GraphQL client and instead use useFetcher to send GraphQL operations to a Remix action that then executes the GraphQL operation.
Let's consider:
We'll have a graphql module that exports functions to execute GraphQL operations (using a GraphQL client or directly with fetch). We can then use these functions in our Remix actions and loaders.
But then how do we do optimistic UI? We can use the useFetcher and then update the UI optimistically before the mutation completes, and then either revert or update when the mutation completes.
Alternatively, we can use a state management solution (like React state) to hold the optimistic data and then update it when the mutation completes.
Since Remix doesn't have a built-in way for optimistic updates, we have to manage it ourselves.
Let's outline:
We'll have a GraphQL client setup (using graphql-request for simplicity) in a module.
We'll create a function for each GraphQL operation (query/mutation) that takes variables and returns a promise.
In our routes, we'll use useFetcher to call an action that runs the GraphQL mutation.
In the component, we'll have local state for the optimistic update. When the user triggers the mutation, we update the local state optimistically and then call the fetcher. If the mutation fails, we revert the optimistic update.
However, note that Remix's useFetcher doesn't provide a built-in way to know when the mutation is done and whether it succeeded or failed? Actually, the fetcher has a state and data and error. We can use that.
But we have to be cautious: the optimistic update might be for a list of items, and we are adding an item. We can update the list by adding the new item optimistically and then when the mutation returns the actual item (with an id) we replace the optimistic item with the real one.
Steps for optimistic update:
We have a list of items from the loader (or from a query). We store that in state (from useLoaderData or useFetcher for queries?).
When we want to add an item, we dispatch an action (via fetcher) and also update the local state by adding the new item (with a temporary id and the data we have).
When the fetcher returns with the new item (with a real id), we replace the temporary item with the real one.
But if the mutation fails, we need to remove the temporary item.
However, note that the list might be coming from a GraphQL query that we are using in multiple places. We might want to have a global state for the list? Or we can keep it in the component that uses the list.
Alternatively, we can use React Query or SWR to manage the cache and optimistic updates. But then we are mixing Remix's data loading with React Query.
Since the requirement is to use Remix, we might stick to Remix's way.
Let me re-think:
We can have:
A route that loads the list of items (using a GraphQL query) and passes it to the component.
The component uses useLoaderData to get the list.
The component also uses useFetcher to handle mutations (add, update, delete).
For optimistic updates, we can maintain a local state that is a copy of the list and update it optimistically, then when the mutation completes, we update the list from the loader again? But that would cause a refetch.
Alternatively, we can update the local state optimistically and then when the mutation returns, we update the local state with the returned data. If there's an error, we revert.
But note: the list from the loader might be stale because other users might have changed it. So we might want to refetch after a successful mutation? But that's not optimistic, that's just updating the cache.
Actually, optimistic UI is about updating the UI before the server responds, assuming the server will accept the change. Then when the server responds, we update with the real data (which might have changes from other users) or if it fails, we revert.
So we can do:
On add:
Create a temporary item (with a temporary id, e.g., temp-${Date.now()}) and add it to the local list.
Call the mutation. When the mutation returns the created item (with a real id and possibly server-generated fields), replace the temporary item with the real one.
On update:
Find the item in the local list and update it with the new data.
Call the mutation. If the mutation returns the updated item, we can update again (if there are server changes) or if it fails, we revert to the old data.
On delete:
Remove the item from the local list (or mark as deleted).
Call the mutation. If it succeeds, we are done. If it fails, we add the item back.
But note: the list from the loader is the source of truth from the server. We are maintaining a local copy that is updated optimistically and then reconciled with the server response.
However, we are not using the loader's data after the initial load? We are using local state. But what if the user navigates away and back? The loader will refetch and we get the server's state.
So we can do:
Use useLoaderData to get the initial list.
Use useState to maintain a local copy of the list (initialized from the loader data).
When the loader data changes (because of a refetch after mutation? or because of navigation) we update the local state? But we don't want to overwrite the optimistic changes.
Actually, we want to keep the optimistic changes until the mutation completes. Then we want to update the local state with the server's response (which might be different from our optimistic update). And then we might want to refetch the entire list to get the latest from the server? But that would be a second request.
Alternatively, we can:
After a successful mutation, we update the local state with the returned data (which is the server's state for that item) and then we also trigger a refetch of the entire list? That would be two updates: one from the mutation response and then another from the refetch.
But if the mutation response returns the updated item, we can just update that item in the local state and not refetch the entire list.
However, what if the mutation causes changes to other items? Then we would miss those. So maybe we should refetch the entire list after a successful mutation? But that's not efficient.
Alternatively, we can use GraphQL subscriptions to update the list in real-time? That's another level.
Given the complexity, let's stick to:
Optimistic updates for the item being mutated.
After the mutation, we refetch the entire list to ensure consistency.
But note: the mutation response might return the entire list? Or we can design our GraphQL mutations to return the affected items (like the created item, or the updated item, or the deleted item's id). Then we can update the local list accordingly and then maybe refetch the list to get any other changes.
However, to keep it simple, we'll do:
On mutation start: update the local state optimistically.
On mutation success: update the local state with the server's response (which might have updated fields) and then refetch the list (using the fetcher to call the loader again?).
On mutation error: revert the local state to the previous state (before the optimistic update).
But note: the loader might have changed in the meantime (because of other mutations by other users). So when we refetch, we get the latest from the server, which might be different from our optimistic update even if our mutation succeeded? Actually, if our mutation succeeded, the server's state should include our change. But if there were concurrent changes, the server's state might be different.
So we are trading off: we show the optimistic update immediately, then when we get the server response we update to the server's state (which might have changed due to concurrency). Then we refetch to get the latest? That might cause a flash.
Alternatively, we can avoid refetching and just update the item with the server's response and then let the user see that. But if there are other changes, we won't see them until the next load.
Given the requirements, let's assume we are okay with the possibility of concurrent updates causing the UI to adjust when we get the server response.
Steps:
We'll have a component that uses useLoaderData to get the initial list.
We'll create a state variable list that is initially the same as the loader data.
We'll also keep a state variable optimisticItems (or a map) to track the optimistic updates? Actually, we can just update the list state optimistically and then when the mutation returns, we update the list again with the server's data. But if the mutation fails, we need to revert. So we need to keep the previous state to revert.
Alternatively, we can use the useFetcher and when the fetcher is submitted, we update the local state optimistically. Then when the fetcher returns, we check if it's successful and then update the local state with the returned data. If it fails, we revert.
But we need to know which item was being mutated to revert? We can store the previous state of that item.
const handleAdd = (newItem) => {
// Create an optimistic item with a temporary id
const optimisticItem = { ...newItem, id: temp-${Date.now()} };
setList(prev => [...prev, optimisticItem]);
code
const formData = new FormData();
formData.append("operation", "addItem");
formData.append("variables", JSON.stringify({ input: newItem }));
fetcher.submit(formData, { method: "post" });
// We'll handle the fetcher response in a useEffect or by checking fetcher.state and fetcher.data.
};
Then in a useEffect:
useEffect(() => {
if (fetcher.state === "idle" && fetcher.data) {
// If the mutation was successful, fetcher.data will have the created item (with real id)
// We want to replace the optimistic item with the real one.
// But how do we know which optimistic item to replace? We can store the temporary id in the fetcher submission? Or we can look for an item with the same unique fields (like name) but that's not reliable.
code
I'll architect a Remix application that combines optimistic UI updates, nested routing, and GraphQL boundaries in a modular, production-ready structure.
# app/graphql/fragments/project.graphql
fragment ProjectSummary on Project {
id
name
description
status
createdAt
updatedAt
owner {
id
name
}
taskCount @client
}
Nested Routing: Remix's file-based routing with _layout.tsx for nested layouts
GraphQL Boundaries:
Single GraphQL endpoint (/api/graphql)
Fragments for reusable data requirements
Modular operation files (queries/mutations)
Type-safe codegen
Progressive Enhancement:
Forms work without JavaScript (Remix action/loader)
Apollo Client enhances with optimistic updates
Error boundaries with recovery mechanisms
Performance:
Cache policies per operation type
Selective fetching with fragments
Background refetching with cache-and-network
Developer Experience:
Full TypeScript support
Generated types from GraphQL schema
Clear separation of concerns
Reusable optimistic components
To Run This Setup:
bash
# Install dependencies
npm install @apollo/client @graphql-yoga/node graphql @graphql-tools/schema @graphql-tools/load-files
# Set up codegen
npm install -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo
# Generate types
npx graphql-codegen
# Start development
npm run dev
This architecture provides:
Instant UI feedback with optimistic updates
Clean, maintainable routing with nested layouts
Strongly-typed GraphQL boundaries
Progressive enhancement out of the box
Excellent developer experience with codegen
Production-ready error handling and caching
// Alternatively, we can return the temporary id from the optimistic update and then in the mutation response, we get the real id and the temporary id? But the server doesn't know about the temporary id.
// So we need a way to map the optimistic item to the server response. We can store the temporary id in the formData and then the server can return the temporary id? No, the server doesn't know about it.
// So we have to match by the data? That's not safe.
// Another idea: when we do the optimistic update, we store the optimistic item in a ref (or state) with a key that we can use to match. For example, we can generate a unique key for the mutation (like a timestamp) and then when the mutation returns, we match by that key? But the server doesn't return that key.
// Alternatively, we can design our GraphQL mutation to return the created item and then we can find the optimistic item by comparing the fields? But if two items have the same fields, we might replace the wrong one.
// So we need a better way.
// Let's change the approach: instead of having a temporary id, we can let the server assign the id and then we update the optimistic item with that id when we get the response. But until then, we don't have an id. So we can have items without ids? That might break our list if we rely on ids for keys.
// We can use a temporary id that we generate and then when the server responds, we replace the entire item (including the temporary id with the real one). But we need to know which item to replace.
// We can store the mapping from temporary id to the optimistic item? Actually, we are adding the optimistic item to the list. So we can search the list for an item that has the same temporary id? But we don't have a temporary id in the item? We did set a temporary id.
// So in the optimistic item, we set `id: temp-${Date.now()}`. Then when the server returns the created item (with a real id), we can find the optimistic item by the temporary id? But we don't have the temporary id in the server response.
// So we need to send the temporary id to the server? The server doesn't need it. So we can store the temporary id in a map in the component state:
const [optimisticMap, setOptimisticMap] = useState({});
Then when we add:
const tempId = `temp-${Date.now()}`;
const optimisticItem = { ...newItem, id: tempId };
setList(prev => [...prev, optimisticItem]);
setOptimisticMap(prev => ({ ...prev, [tempId]: optimisticItem }));
Then when the mutation returns, we get the real item. We can remove the temporary item and add the real one? But we don't have the temporary id in the response.
So we need to send the temporary id as a variable to the mutation? And then the mutation can return it? But the mutation doesn't use it.
Alternatively, we can store the temporary id in the fetcher's submission and then when the fetcher returns, we can get the temporary id from the submission? We can use `fetcher.submit` with a `formData` that includes the temporary id as a variable? Then in the action, we can return the temporary id in the response? But the action doesn't know about the temporary id because it's not used in the mutation.
So let's change the action:
In the action, we run the GraphQL mutation and then we return the created item. But we don't have the temporary id. So we cannot match.
Alternatively, we can do:
In the component, when we get the response, we can find the optimistic item by comparing the data (like the name and other fields) and then replace it. But that's risky.
Given the complexity, maybe we should use a GraphQL client that handles optimistic updates for us, like Apollo Client. But then we are not using Remix's data loading.
Since the requirement is to use Remix, let's stick to Remix's way and avoid a full GraphQL client.
Another idea: instead of adding the optimistic item to the list, we can have a separate list for optimistic items? Then when the mutation returns, we remove the optimistic item and add the real one. But then we have two lists to merge.
Let's do:
const [list, setList] = useState(loaderData.items);
const [optimisticAdds, setOptimisticAdds] = useState([]);
Then when adding:
const tempId = `temp-${Date.now()}`;
const optimisticItem = { ...newItem, id: tempId };
setOptimisticAdds(prev => [...prev, optimisticItem]);
Then the displayed list is [...list, ...optimisticAdds].
Then when the mutation returns, we remove the optimistic item (by tempId) and add the real item to the list.
But then we have to manage two states.
Alternatively, we can have a single list state and mark optimistic items with a flag:
const [list, setList] = useState(loaderData.items);
Then when adding:
const tempId = `temp-${Date.now()}`;
const optimisticItem = { ...newItem, id: tempId, __optimistic: true };
setList(prev => [...prev, optimisticItem]);
Then when the mutation returns, we find the item with __optimistic and the same data? But again, we don't have the tempId in the response.
So we are back to the same problem.
Given the time, let's simplify:
We'll do optimistic update without trying to replace the temporary item with the real one. Instead, when the mutation returns, we will refetch the entire list. Then the list will be updated with the server's state, which includes the new item (with real id). The optimistic item will be replaced by the real one because the refetched list doesn't have the temporary item.
Steps:
- When adding: add an optimistic item (with temporary id) to the local list.
- When the mutation completes (success or error), we refetch the list (by calling the loader again via fetcher for the query?).
But then if the mutation fails, we refetch and the optimistic item is gone (because the server didn't save it) and we get the old list. That's acceptable.
If the mutation succeeds, we refetch and get the new list with the real item. The optimistic item is gone and replaced by the real one.
So we don't need to match the optimistic item with the real one. We just refetch.
But note: the refetch might be expensive and we are doing it on every mutation. But for simplicity, it's acceptable.
How to refetch the list?
We can have a fetcher for the query that loads the list. We can trigger that fetcher when the mutation fetcher completes.
So we have two fetchers: one for the mutation and one for the query.
Alternatively, we can use the same fetcher for both? But the query and mutation are different operations.
Let's set up:
In the component:
const queryFetcher = useFetcher();
const mutationFetcher = useFetcher();
The queryFetcher will be used to load the list (by calling the loader of the current route? or a specific route that returns the list). But we are already in a route that has a loader that returns the list. So we can use the same route's loader? But the loader is called when the route is loaded. We want to refetch the same loader.
We can do:
useEffect(() => {
if (mutationFetcher.state === "idle" && mutationFetcher.data) {
// Refetch the list
queryFetcher.load("/current-route-path");
}
}, [mutationFetcher.state, mutationFetcher.data]);
But note: the queryFetcher.load will call the loader of the current route and then we can get the new list from queryFetcher.data.
Then we update the local list state with queryFetcher.data.items.
But then we are storing the list in two places: the loader data and the component state? We are using the component state to show the optimistic update, and then when the queryFetcher returns, we update the component state with the new list.
Alternatively, we can just use the queryFetcher.data as the list and when we do an optimistic update, we update the queryFetcher.data? But we cannot because queryFetcher.data is read-only.
So we need a local state that is initially from the loader, then we update it optimistically, and then when the queryFetcher returns, we set the local state to the new data.
Steps:
1. Initial list: from useLoaderData (or from queryFetcher.data if we are using queryFetcher for the initial load?).
Let's use:
const [list, setList] = useState(loaderData.items);
But then we want to refetch and update the list when the queryFetcher returns.
We can do:
useEffect(() => {
if (queryFetcher.data) {
setList(queryFetcher.data.items);
}
}, [queryFetcher.data]);
And then when we do an optimistic update, we update the `list` state.
Then when the mutationFetcher completes, we trigger the queryFetcher to load again.
But note: the initial load is from the loader, and then we update the state from the queryFetcher. That's okay.
However, we are using two fetchers and we are refetching the entire list after every mutation.
This is a simple approach.
Let's code:
In the component:
const { items: initialItems } = useLoaderData();
const [list, setList] = useState(initialItems);
const queryFetcher = useFetcher();
const mutationFetcher = useFetcher();
// Update the list when queryFetcher returns new data
useEffect(() => {
if (queryFetcher.data) {
setList(queryFetcher.data.items);
}
}, [queryFetcher.data]);
// When mutationFetcher completes (success or error), refetch the list
useEffect(() => {
if (mutationFetcher.state === "idle" && mutationFetcher.data) {
queryFetcher.load("/current-route-path");
}
}, [mutationFetcher.state, mutationFetcher.data]);
Then when adding:
const handleAdd = (newItem) => {
const optimisticItem = { ...newItem, id: `temp-${Date.now()}` };
setList(prev => [...prev, optimisticItem]);
const formData = new FormData();
formData.append("operation", "addItem");
formData.append("variables", JSON.stringify({ input: newItem }));
mutationFetcher.submit(formData, { method: "post" });
};
This way, we don't need to worry about matching the optimistic item with the real one.
But note: the mutation might fail, and then we refetch and the optimistic item is gone. That's acceptable.
However, the user might see the optimistic item and then it disappears. That's the nature of optimistic updates: if the mutation fails, we remove the optimistic item.
But what if the mutation fails and we want to show an error? We can show an error message from mutationFetcher.data?.errors.
Now, for nested routing:
We'll structure the routes with nested layouts. For example:
/dashboard
/dashboard/index (list of items)
/dashboard/item/$id (detail of an item)
We can have a layout at /dashboard that shows a sidebar and then the children.
For GraphQL boundaries:
We can have a module for GraphQL operations. We'll define:
- graphql/
- mutations.js
- queries.js
- fragments.js
And then in our actions and loaders, we import the necessary operations and execute them.
We'll set up a GraphQL client (using graphql-request) in a separate module.
Example:
// app/graphql/client.js
import { GraphQLClient } from 'graphql-request';
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {
headers: {
authorization: `Bearer ${process.env.AUTH_TOKEN}`,
},
});
export default client;
Then in an action:
// app/routes/dashboard.jsx (or .tsx)
import client from '~/graphql/client';
import { addItemMutation } from '~/graphql/mutations';
export const action = async ({ request }) => {
const formData = await request.formData();
const operation = formData.get('operation');
const variables = JSON.parse(formData.get('variables'));
if (operation === 'addItem') {
const data = await client.request(addItemMutation, variables);
return data;
}
};
But note: we are using the same endpoint for all operations. And we are using the same client.
However, we might want to have different clients for different parts of the app? But usually one client is enough.
Now, for the loader:
import client from '~/graphql/client';
import { itemsQuery } from '~/graphql/queries';
export const loader = async () => {
const data = await client.request(itemsQuery);
return data;
};
But note: the loader runs on the server, and the client is set up with the endpoint and headers. This is fine.
However, we are using environment variables for the endpoint and token. We must set them.
Now, for nested routing:
We'll have:
app/routes/dashboard.jsx (the layout)
app/routes/dashboard/index.jsx (the list)
app/routes/dashboard/item/$id.jsx (the detail)
In dashboard.jsx (the layout):
import { Outlet } from '@remix-run/react';
export default function DashboardLayout() {
return (
<div>
<nav>...</nav>
<Outlet />
</div>
);
}
In dashboard/index.jsx:
We have the list of items and the form to add a new item.
We use the loader and action as described above.
In dashboard/item/$id.jsx:
We have a loader that loads a single item by id.
But note: we are using the same GraphQL client. We can have a query for a single item.
Now, the challenge is that the optimistic update in the list might be for an item that is being viewed in the detail? We don't have to worry about that because the detail route will have its own loader that loads the item from the server. So when we navigate to the detail of an optimistic item (with a temporary id), the loader will try to load by that id and fail. So we might want to avoid navigating to an optimistic item? Or we can handle it by showing an error in the detail.
Alternatively, we can design the detail route to handle the case when the item is not found (which will be the case for a temporary id). But then we might want to wait until the mutation completes and the item gets a real id.
That's a more advanced scenario.
Given the time, we'll keep it simple and not handle navigation to optimistic items.
Summary:
- We set up a GraphQL client and define operations in separate files.
- We use Remix loaders and actions to execute GraphQL operations.
- In the list component, we use a local state for the list and a queryFetcher to refetch the list after mutations.
- We do optimistic updates by adding an item with a temporary id and then refetching the list after the mutation.
This is a basic setup. There are many edge cases and improvements possible.
Let's code the structure:
Project structure:
app/
graphql/
client.js
mutations.js
queries.js
fragments.js
routes/
dashboard.jsx (layout)
dashboard/
index.jsx
item/
$id.jsx
root.jsx
entry.client.jsx
entry.server.jsx
We'll use TypeScript? The problem says "Remix app", so we can use JavaScript or TypeScript. I'll use JavaScript for simplicity.
Let's write some code:
app/graphql/client.js:
import { GraphQLClient } from 'graphql-request';
const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {
headers: {
authorization: `Bearer ${process.env.AUTH_TOKEN}`,
},
});
export default client;
app/graphql/mutations.js:
export const addItemMutation = `
mutation AddItem($input: ItemInput!) {
addItem(input: $input) {
id
name
description
}
}
`;
app/graphql/queries.js:
export const itemsQuery = `
query Items {
items {
id
name
description
}
}
`;
export const itemQuery = `
query Item($id: ID!) {
item(id: $id) {
id
name
description
}
}
`;
app/routes/dashboard.jsx:
import { Outlet } from '@remix-run/react';
export default function DashboardLayout() {
return (
<div>
<h1>Dashboard</h1>
<nav>
<ul>
<li><a href="/dashboard">Items</a></li>
</ul>
</nav>
<Outlet />
</div>
);
}
app/routes/dashboard/index.jsx:
import { useLoaderData, useFetcher, useEffect, useState } from '@remix-run/react';
import client from '~/graphql/client';
import { itemsQuery } from '~/graphql/queries';
import { addItemMutation } from '~/graphql/mutations';
export const loader = async () => {
const data = await client.request(itemsQuery);
return data;
};
export const action = async ({ request }) => {
const formData = await request.formData();
const operation = formData.get('operation');
const variables = JSON.parse(formData.get('variables'));
if (operation === 'addItem') {
const data = await client.request(addItemMutation, variables);
return data;
}
};
export default function DashboardIndex() {
const { items } = useLoaderData();
const [list, setList] = useState(items);
const queryFetcher = useFetcher();
const mutationFetcher = useFetcher();
// Update the list when queryFetcher returns new data
useEffect(() => {
if (queryFetcher.data) {
setList(queryFetcher.data.items);
}
}, [queryFetcher.data]);
// When mutationFetcher completes (success or error), refetch the list
useEffect(() => {
if (mutationFetcher.state === "idle" && mutationFetcher.data) {
queryFetcher.load("/dashboard");
}
}, [mutationFetcher.state, mutationFetcher.data]);
const handleAdd = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const name = formData.get('name');
const description = formData.get('description');
const newItem = { name, description };
const optimisticItem = { ...newItem, id: `temp-${Date.now()}` };
setList(prev => [...prev, optimisticItem]);
const mutationFormData = new FormData();
mutationFormData.append('operation', 'addItem');
mutationFormData.append('variables', JSON.stringify({ input: newItem }));
mutationFetcher.submit(mutationFormData, { method: 'post' });
};
return (
<div>
<h2>Items</h2>
<form onSubmit={handleAdd}>
<input name="name" placeholder="Name" required />
<input name="description" placeholder="Description" />
<button type="submit">Add</button>
</form>
<ul>
{list.map(item => (
<li key={item.id}>
{item.name} - {item.description}
<a href={`/dashboard/item/${item.id}`}>View</a>
</li>
))}
</ul>
{mutationFetcher.data?.errors && (
<p>Error: {mutationFetcher.data.errors[0].message}</p>
)}
</div>
);
}
app/routes/dashboard/item/$id.jsx:
import { useLoaderData, useFetcher } from '@remix-run/react';
import client from '~/graphql/client';
import { itemQuery } from '~/graphql/queries';
export const loader = async ({ params }) => {
const { id } = params;
const data = await client.request(itemQuery, { id });
return data;
};
export const action = async ({ request, params }) => {
// We might have update and delete mutations here.
};
export default function ItemDetail() {
const { item } = useLoaderData();
// ... display item and maybe edit form
}
This is a basic structure.
Note: We are using the same route for the queryFetcher.load("/dashboard") which will call the loader of the dashboard index route.
Also, note that the mutationFetcher and queryFetcher are separate. We are using the queryFetcher to refetch the list.
This approach works but has some drawbacks:
- We are refetching the entire list after every mutation, which might be inefficient for large lists.
- We are not updating the list with the server's response for the mutated item, but with the entire list from the server. This is safe but might be slower.
Alternatively, we could update the list with the server's response (the created item) without refetching the entire list. But then we have to match the optimistic item with the real one. We can do:
In the mutationFetcher's response, we get the created item (with real id). We can then update the list by:
setList(prev => {
// Remove the optimistic item (with temporary id) and add the real item.
// But we don't have the temporary id in the response.
// So we can store the temporary id in the formData and then return it in the response? We can modify the action to return the temporary id?
// We can send the temporary id as a variable to the mutation? But the mutation doesn't need it.
// We can return the temporary id from the action? We can do:
// In the action, we don't have the temporary id. So we cannot.
// So we have to match by the data? Not safe.
// Therefore, the refetch approach is simpler and safer.
Given the time, we'll stick with the refetch.
This is a basic architecture. There are many improvements possible, but this meets the requirements:
- Optimistic UI: we add the item immediately and then refetch.
- Nested routing: we have a layout and nested routes.
- GraphQL boundaries: we have a separate module for GraphQL operations and we use a client.
However, note that we are using the same GraphQL client for all operations and we are not using fragments or typed documents. We can improve by using `@graphql-typed-document-node/core` to have typed GraphQL documents.
But for simplicity, we are using template literals.
Also, we are not handling errors in the optimistic update: if the mutation fails, we refetch and the optimistic item disappears. We show an error message.
This is a starting point.
Let me know if you have any questions.</think>