Closed thaiphan closed 3 years ago
You could either have a slice listen to actions from your endpoint and save it to the side or use a (memoizing) selector in combination with the hook. (https://rtk-query-docs.netlify.app/concepts/queries#selecting-data-from-a-query-result)
Generally, rtk-query did not have the design goal of returning normalized data. In most cases I'd just have a query to retrieve a single item from the server and use that where applicable. Since most "lists" display less data than "single item views", in the end you probably even save some transmitted data by only retrieving necessary data for the list in the "list query" and only receiving the full data for a single item should you need it. But of course that requires some control over your api endpoints on the server or a protocol like graphql.
I don't have much control over the API, which is quite limited in what it can do in some situations. However, I figured out an alternate method from yours that seems to work.
I can do something like...
const organizationsApi = createApi({
baseQuery: fetchBaseQuery({
baseUrl: '/organizations/',
}),
endpoints: (builder) => {
getTeams: builder.query({
query: (organizationId) => `${organizationId}/teams`,
}),
}
})
And then...
const teamsAdapter = createEntityAdapter({
selectId: (team) => team.id,
});
const teamsSlice = createSlice({
name: 'teams',
extraReducers: (builder) => {
builder.addMatcher(organizationsApi.endpoints.getTeams.matchFulfilled, (state, action) => {
teamsAdapter.setAll(state, action.payload.result);
});
}
})
Is this approach something you'd be fine with or is it bad practice?
That is essentially the first option I hinted at. You can do this, but you have to be aware that this data will linger around indefinitely even if no more component using it is mounted. The RTK-Query cache will be cleared of that data after 60 seconds of non-usage. That's why I would prefer selectFromResult
in this case.
Yep thanks for that. The data will be required for the entirety of the app so I think it should be fine.
It would be great if we could use this properly in conjunction with createEntityAdapter
however. Not sure how it'd look but the less boilerplate the better!
Well, as I said: we are not doing any normalization, we just cache api results endpoint per endpoint. There are no plans to change that as well. But of course you can do normalization yourself in the end.
Okay so I love that i can download and cache collections with ease. However, I need to be able to get a specific object from my collection and not have to iterate through each time.
Do you have any suggestions on how I could go about integrating this with
createEntityAdapter
?