Replies: 1 comment 4 replies
-
You can use a better approach directly in the definition of your endpoints. import { rootApi } from "../api";
import { nanoid } from "@reduxjs/toolkit";
export const commentApi = rootApi.injectEndpoints({
tagTypes: ['Comments'],
endpoints: (builder) => ({
createComment: builder.mutation({
query: (data) => ({
url: `comments`,
type: 'POST',
data
}),
async onQueryStarted(data, { dispatch, queryFulfilled }) {
// (Optionnal) RTK is re-exporting the nanoid() helper function. You can use this to generate an id
const TEMP_ID = nanoid();
// Update the query data with a temporary identifier
const patchResult = dispatch(
commentApi.util.updateQueryData('fetchComments', null, (draft) => {
draft.push({
id: TEMP_ID,
user: auth,
content: data.content,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
});
})
);
try {
// Wait for the API response
const result = await queryFulfilled;
// Update the query data with the correct id from the API success response
dispatch(
commentApi.util.updateQueryData('fetchComments', null, (draft) => {
const index = draft.findIndex(item => item.id === TEMP_ID);
if (index !== -1) {
draft[index] = result.data;
}
})
);
} catch {
// Undo the patch if the API call failed
patchResult.undo();
// (Optionnal) invalidate the cache
dispatch(commentApi.util.invalidateTags(['Comments']));
}
},
}),
fetchComments: builder.query({
providesTags: () => ['Comments'],
query: () => `comments`,
}),
}),
}); |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
hey, I have a comments list, when the user adds a new comment I want to update the list immediately before I send the API request,
and when the API response with an error I just simply
undo
the update, but the thing that concerns me is that each comment has the user and its unique id which I won't have until the I get the API response so I am assuming that the comment user is already the auth user and the id is aTEMP_ID
and update the list according to that and when I have the API response what I'm doing is that:TEMP_ID
here is how I am doing it:
so my question is: updating the list in this way is it right or there is something better I can do?
Beta Was this translation helpful? Give feedback.
All reactions