Keep page state on navigating back from a product to the product list

I have an e-commerce site which fetches product collections using trpc. I want to be able to keep this page state the same when navigating back, so that the user is back to the previous position they were at. I was thinking there has to be some way to cache the previous page so it does not reload but am not sure where to look. Here is the component in question:
"use client";
import { Suspense, useState } from "react";

import { api } from "~/trpc/react";
...

export function ProductList({ collection }: { collection: Collection }) {
const [sortOption, setSortOption] = useState<SortOption>(sortOptions[1]!);

const [products] = api.product.getFromCollection.useSuspenseQuery(
{
collection: collection.handle,
sortKey: sortOption.key,
reverse: sortOption.reverse,
},
);

...
{/* Product List wrapped in a suspense */}
<div className="grid w-full gap-3 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4">
<Suspense
fallback={Array.from({ length: 12 }, (_, key) =>
key.toString(),
).map((key) => (
<Skeleton
key={key}
className="h-[20px] w-[100px] rounded-full"
/>
))}
>
{products.map((product, index) => (
<ProductTile
key={product.handle}
product={product}
position={index}
/>
))}
</Suspense>
</div>
...
"use client";
import { Suspense, useState } from "react";

import { api } from "~/trpc/react";
...

export function ProductList({ collection }: { collection: Collection }) {
const [sortOption, setSortOption] = useState<SortOption>(sortOptions[1]!);

const [products] = api.product.getFromCollection.useSuspenseQuery(
{
collection: collection.handle,
sortKey: sortOption.key,
reverse: sortOption.reverse,
},
);

...
{/* Product List wrapped in a suspense */}
<div className="grid w-full gap-3 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4">
<Suspense
fallback={Array.from({ length: 12 }, (_, key) =>
key.toString(),
).map((key) => (
<Skeleton
key={key}
className="h-[20px] w-[100px] rounded-full"
/>
))}
>
{products.map((product, index) => (
<ProductTile
key={product.handle}
product={product}
position={index}
/>
))}
</Suspense>
</div>
...
2 Replies
Timmo
TimmoOP2mo ago
The only alternative I can think of is to store the product slug in the page history and fast scroll to that previous position. The faster and cleaner the better for UX though
Sturlen
Sturlen5w ago
if you want to keep state between navigation or refreshes, then storing it in the URL is a good choice. e.g. /produts?filter=shoes&sort=asc. you can do this manually, but there are libraries like tanstack-router that make this easier. tRPC/react-query also caches your results, so as long as you call it with the same sorting and filtering options. this means the user will see the previous results immediately when navigating back
Want results from more Discord servers?
Add your server