Repository navigation
Replies: 1 comment
|
If the host apps already use RTK Query and their base queries accept the same request shape, the shared package can export an endpoint installer. Each host calls it once with its own API slice: // Shared comments package
export function addCommentsEndpoints(api) {
return api.injectEndpoints({
endpoints: build => ({
sharedGetComments: build.query({
query: postId => ({ url: '/comments', params: { postId } }),
providesTags: (_data, _error, postId) => [{ type: 'Comments', id: postId }],
}),
sharedAddComment: build.mutation({
query: ({ postId, text }) => ({
url: '/comments', method: 'POST', body: { postId, text },
}),
invalidatesTags: (_data, _error, { postId }) => [{ type: 'Comments', id: postId }],
}),
}),
});
}
// Host app, at module scope
const commentsApi = addCommentsEndpoints(hostApi);
export const { useSharedGetCommentsQuery, useSharedAddCommentMutation } = commentsApi;Use In a two-store test on RTK 2.14.0, calls for the same post deduplicated within a host, and a comment mutation refreshed that host's query without touching the other host. This pattern uses the host's base query. If the comments service needs its own transport or authentication, your option 3 is a good fit. Endpoint injection · Store integration |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
I have a set of separate single-page applications, each of which has its own build process and RTK setup. I also have a library of components that are used across these apps. I am wondering about good approaches for handling data-fetching for these components.
Take for example a comments component, which would be used to perform various CRUD operations on a list of comments from a comments API. I can think of a few options for doing this, but would look like to know if there are better approaches I should consider.
Option 1.
Just do the data-fetching within each of the parent applications independently (using RTK query), and pass the relevant return values from the useQuery hooks (data, isFetching, isError) etc into the comments component, along with callbacks for carrying out mutations.
Option 2.
Handle the data-fetching & mutating entirely within the comments component. Possibly using its own completely independent RTK setup and redux store, or not using redux at all in these components and just using a lighter-weight data-fetching library e.g. swr.
Option 3
Create an api slice with createApi within the comments component and export the middleware and reducers, for the parent application to include them when configuring its store. This should work fine but it creates a bit more setup work on the side of the parent application.
Any other good contenders?
All reactions