-
I'm totally confused by This is my requirement: i want to get an object with id 123 via What should I do? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 5 replies
-
Here's my code: export async function loader({
params,
}: LoaderFunctionArgs) {
const id = params.id
const info = fetch(`https://example.com/info/${id}`)
.then(r => r.json() as string)
return defer({ info: info })
}
export async function clientLoader({
serverLoader,
}: ClientLoaderFunctionArgs) {
const { info } = await serverLoader<typeof loader>()
//other fetch()s
return info;
}
clientLoader.hydrate = true
export function HydrateFallback() {
return <div>Loading...</div>
} Is there a better way? |
Beta Was this translation helpful? Give feedback.
-
In your case it is probably not necessary to use Like this export async function loader({
params,
}: LoaderFunctionArgs) {
const id = params.id
const info = fetch(`https://example.com/info/${id}`)
.then(r => r.json() as string)
return defer({ info: info })
}
export default Route() {
// here is the promise from `defer`
const loaderData = useLoaderData
return (
<Suspense fallback={<div>Loading...</div>}>
<Await resolve={loaderData.info} errorElement={<div>Error</div>}>
{/* here is the resolved data */}
{(info) => <p>{info}</p>}
<Await>
</Suspense>
)
}
For reference — Await |
Beta Was this translation helpful? Give feedback.
-
Use I think most of the time you should go for The In your case, for the requirement to show a fallback while the fetch to the API is in progress, you can use You can combine this with more fetches if you need, which could also be deferred or not. function fetchInfo(id: string) {
return fetch(`https://example.com/info/${id}`).then(r => r.json() as Info)
}
export async function loader({
params,
}: LoaderFunctionArgs) {
const info = fetchInfo(params.id)
// here you can start loading more data
const data = await getMoreData()
return defer({ info, data })
} Because you The benefit of this is that you kickstart the And if you want, you can remove the |
Beta Was this translation helpful? Give feedback.
Use
loader
when you want to load data server-side, useclientLoader
when you want to load data client-side.I think most of the time you should go for
loader
and load data server-side, you won't have to think about CORS, server-to-server requests are typically faster and with more predictable latency, you could use a server-side cache either per user or shared across users, or use an http cache to cache the whole response to one or all users.The
clientLoader
is great for things that are only available client-side (e.g. callnavigator.getCurrentLocation
orlocalStorage.getItem
).In your case, for the requirement to show a fallback while the fetch to the API is in progress, you can use
defer
…