Created
February 28, 2024 08:53
-
-
Save MattyBalaam/5d63c6af4774a3c8a47e63658c33f704 to your computer and use it in GitHub Desktop.
Remix use loader timestamp to select most recent data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { json, LoaderFunctionArgs } from "@remix-run/node"; | |
import { | |
Form, | |
Link, | |
useFetcher, | |
useLoaderData, | |
useSearchParams, | |
} from "@remix-run/react"; | |
export const loader = async ({ request }: LoaderFunctionArgs) => { | |
const searchParams = new URL(request.url).searchParams; | |
const value = searchParams.get("search"); | |
const color = searchParams.get("color"); | |
console.log({ color, value }); | |
return json({ | |
time: new Date().toISOString().split("T").at(-1), | |
color, | |
timestamp: Date.now(), | |
}); | |
}; | |
export function useFetcherOrLoaderData() { | |
const loaderData = useLoaderData<typeof loader>(); | |
const fetcher = useFetcher<typeof loader>(); | |
return { | |
...fetcher, | |
data: | |
fetcher.data && fetcher.data.timestamp > loaderData.timestamp | |
? fetcher.data | |
: loaderData, | |
}; | |
} | |
const TestRoute = () => { | |
const fetcher = useFetcherOrLoaderData(); | |
const [searchParams] = useSearchParams(); | |
return ( | |
<div style={{ background: fetcher.data?.color || "" }}> | |
<Form> | |
<h1>{fetcher?.data?.time}</h1> | |
<input | |
name="search" | |
onChange={({ currentTarget: { value } }) => { | |
// send request, but do not update urls - we only want this when the form submits | |
fetcher.submit({ search: value, color: fetcher.data.color }); | |
}} | |
/> | |
{/* hidden field to resubmit color value */} | |
<input name="color" type="hidden" value={fetcher.data.color || ""} /> | |
<ul> | |
{["red", "green", "lightgrey", ""].map((color) => { | |
const newSearchParams = new URLSearchParams(searchParams); | |
// we need to create a link which includes the current search | |
newSearchParams.set("color", color); | |
return ( | |
<li key={color}> | |
<Link to={`/?${newSearchParams.toString()}`}> | |
{color || "default"} | |
</Link> | |
</li> | |
); | |
})} | |
</ul> | |
</Form> | |
</div> | |
); | |
}; | |
export default TestRoute; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment