Maintaining a global state without Redux #1479
-
I'm building an application which relies on the GitHub graphql api. API calls happen in my routes data loaders, and I'm fetching the rateLimit information on each call, to see where's my usage at. I would like to be able to display the rateLimit info in my application footer, which is rendered in my root.tsx. Usually, I would use Redux to store and fetch this information and display it. My first guess was to use something like demoed in the sharing-loader-data example, especially the index.tsx part, but I'm unsure how to find the match that performed the last API call. Any pointers towards a clean way to achieve this would be highly appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
From the top of my head, untested: Make sure to pass a current timestamp to each loader's Response: type LoaderData = {
timestamp: number;
// Your API response, including:
rateLimit: RateLimit;
};
// simplified, adapt to your actual implementation:
export const loader: LoaderFunction = async () => {
const githubData = await getGithubData();
// Of course, this timestamp represents the point in time
// you _received_ the API response and not the moment
// it was sent. Might be good enough for your use case.
const timestamp = new Date().getTime();
return json<LoaderData>({
...githubData,
timestamp,
});
}; Then, in the component that renders your footer, find the match with the most recent timestamp, take its import { useMatches, Outlet } from "remix";
export default function Layout() {
const matches = useMatches();
const mostRecentMatch = matches.reduce((result, match) =>
match.data.timestamp > result.data.timestamp ? match : result
);
return (
<>
<header>...</header>
<main>
<Outlet />
</main>
<footer>
{/* Do whatever you want with `rateLimit` */}
{mostRecentMatch.data.rateLimit}
</footer>
</>
);
} |
Beta Was this translation helpful? Give feedback.
From the top of my head, untested: Make sure to pass a current timestamp to each loader's Response:
Then, in the component that renders your footer, find …