Actually it is pretty simple, but I had to refactor the code.
I created new api for each logical part. So to invalidate cache I would have to reset each api's state individually.
Fortunately rtk
has code splitting capabilities in it:
https://redux-toolkit.js.org/rtk-query/usage/code-splitting
Basically you create baseApi
likes this:
export const baseApi = createApi({
baseQuery: fetchBaseQuery({
baseUrl: `${BASE_URL}/api`,
prepareHeaders: (headers, { getState }) => {
const token = (getState() as RootState).auth.token;
if (token) {
headers.set("authorization", `Bearer ${token}`);
}
return headers;
},
}),
tagTypes: ["Vehicle", "CompanySetting", "Associate"],
endpoints: () => ({}),
});
Then you can add api slice to it in a separate file, like so:
export const companySettingsApi = baseApi.injectEndpoints({
endpoints: (builder) => ({
getCompanySettings: builder.query<CompanySetting[], void>({
query: () => ({
url: `/companySettings`,
}),
providesTags: (_) => ["CompanySetting"],
}),
setCompanySettings: builder.mutation<void, CompanySetting[]>({
query: (companySettings) => ({
url: `/companySettings`,
method: "PUT",
body: companySettings,
}),
invalidatesTags: (_) => ["CompanySetting"],
}),
}),
});
This gives you ability to reset entire api state with a single dispatch
dispatch(baseApi.util.resetApiState());