In React, is there a way to get composition for queries which take variables? #1215
Unanswered
tonyketcham
asked this question in
Q&A
Replies: 1 comment 1 reply
-
I tried wrapping the function preparePostsByUserQuery(userId: string) {
const { preload, refetch, usePrepared, callback } = prepareQuery((query: Query) =>
query.posts({
where: createdBy: {
equals: userId,
},
}),
);
return {
preload,
refetch,
usePrepared,
callback,
};
}
const PostsQueryContext = createContext<ReturnType<typeof preparePostsByUserQuery> | null>(null);
function PostsQueryProvider({ userId, children }: { userId: string; children: React.ReactNode }) {
const postsQuery = preparePostsByUserQuery(userId);
console.log(postsQuery); // this always prints {preload: undefined, refetch: undefined, usePrepared: undefined, callback: undefined}
const value = useMemo(() => postsQuery, [projectsQuery]);
return <PostsQueryContext.Provider value={value}>{children}</PostsQueryContext.Provider>;
} Then using inside of a component with optional chaining in case GQty is returning const postsQuery = useContext(PostsQueryContext);
const query = postsQuery?.usePrepared?.();
console.log({ query }); // this prints {query: undefined} |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
For static queries which don't rely on variables at runtime, it's possible to use
prepareQuery
to get compositional usage of a query across component boundaries.However, if I have a query which takes a runtime argument known by a React component, such as fetching posts by a particular
userId
, and wish to use or refetch that query in multiple components (even just in a parent component and its children),prepareQuery
does not seem to be a viable option. Is there a pattern for creating one shared query reference which can do this? Perhaps stored in a shared context?Attempting to pass a
const query = useQuery(...)
instance across component boundaries as a prop seems to break the reference and does not work for triggering refetches, etc.Beta Was this translation helpful? Give feedback.
All reactions