On this page, I need to cache my API function because I need the same data in both the Page, as well as in the generateMetadata
function.
Since I'm using Axios, and not fetch, the deduplication doesn't happen automatically and I have to wrap my API call into React's cache
function instead.
Problem is, if I navigate to another page and back to this one, I'm receiving the same old state data. What I want instead is the same behavior of getServerSideProps where we always load fresh data from the server.
import * as UsersApi from "@/network/api/users";
import { notFound } from "next/navigation";
import { NotFoundError } from "@/network/http-errors";
import UserProfilePage from "./UserProfilePage";
import { Metadata } from "next";
import { cache } from "react";
interface PageProps {
params: { username: string; }
};
// TODO: How can I dedupe requests without getting stale data on page navigation?
const getUser = cache(UsersApi.getUserByUsername);
export async function generateMetadata({ params: { username } }: PageProps): Promise<Metadata> {
try {
const user = await getUser(username);
return {
title: `${user.username} - Flow Blog`,
};
} catch (error) {
if (error instanceof NotFoundError) {
notFound();
} else {
throw error;
}
}
}
export default async function Page({ params: { username } }: PageProps) {
const user = await getUser(username);
return <UserProfilePage user={user} />;
}