How to update the context set in a route loader? #10420
-
I am using This gives me access to the data in any route. export const loader = async ({ request, context, params }: LoaderFunctionArgs) => {
const user = await getUser();
const features = await getFeatures();
return { user, features };
} I have certain parts of the application where I want to refresh that data, or change the value used in that context, client side. Is there a way I can set the values that would be returned in that loader data, without refreshing the entire page? I see there's a |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 1 reply
-
You are about to make the code more likely to produce stale results with added complexity and bugs by spreading something that should be one function into different concepts and places. I recommend to decide whether you want the data from the loader or you have it on the client and some logic to refresh it. There are many different ways doing it, but with the info provided its impossible to tell what is the best way. |
Beta Was this translation helpful? Give feedback.
-
You could create a react context in the root route and pass it down. Initialize it with the (root) loader data once, provide with the context a function to update the data using either web fetch or remix fetcher.load(...) on an API route. You could bundle this all up in once place, the context and the hook to get the context and API. |
Beta Was this translation helpful? Give feedback.
-
Makes sense - thanks for your help! |
Beta Was this translation helpful? Give feedback.
-
The context received by loaders and actions, called AppLoadContext, can't be changed from inside loaders and actions, that context is used by the HTTP server to inject values into the Remix loaders/actions. Also React context won't work in loaders and actions, they run outside React and in the server, so you can't call And if you want to share data from a parent route to children routes instead of creating a custom context you can use the |
Beta Was this translation helpful? Give feedback.
The context received by loaders and actions, called AppLoadContext, can't be changed from inside loaders and actions, that context is used by the HTTP server to inject values into the Remix loaders/actions.
Also React context won't work in loaders and actions, they run outside React and in the server, so you can't call
useContext
inside your loaders and actions.And if you want to share data from a parent route to children routes instead of creating a custom context you can use the
useRouteLoaderData
hook, if you want to access the root loader data you can douseRouteLoaderData("root")
, other routes will need you to pass the route id.