Update Slice State After Manual Cache Update #4403
-
Hi everyone, I'm facing an issue where the state of a Any suggestions on how to ensure the property recalculates after manual cache updates would be appreciated. Thanks. const userSlice = createSlice({
name: "userSlice",
initialState: { usersAmount: 0 },
reducers: {},
extraReducers: (builder) => {
builder.addMatcher(
usersApi.endpoints.getUsers.matchFulfilled,
(state, { payload }) => {
state.usersAmount = payload.length;
},
);
},
});
const usersApi = mainApi.injectEndpoints({
endpoints: (builder) => ({
getUsers: builder.query<TUser[], void>({
query: () => `${usersBaseUrl}/users`,
}),
deleteUser: builder.mutation<void, string>({
query: (userId) => ({
url: `${usersBaseUrl}/users/${userId}`,
method: "DELETE",
}),
async onQueryStarted(userId, { dispatch, queryFulfilled }) {
try {
await queryFulfilled;
dispatch(
usersApi.util.updateQueryData("getUsers", undefined, (prevData) =>
prevData.filter((user) => user.id !== userId),
),
);
} catch {}
},
})
}),
});
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
are you editing userAmount anywhere else, or is it purely derived from the query data? |
Beta Was this translation helpful? Give feedback.
-
I assume that there is no possibility to auto trigger |
Beta Was this translation helpful? Give feedback.
there is no action dispatched that would be useful to you, no - the only action actually dispatched contains JSON patches of your changes that are applied in the reducer itself.
https://github.com/reduxjs/redux-toolkit/blob/master/packages/toolkit/src/query/core/buildSlice.ts#L130
https://github.com/reduxjs/redux-toolkit/blob/master/packages/toolkit/src/query/core/buildThunks.ts#L251