I have implemented succesfully an optimistic update in redux-toolkit. But I am not able to type it correctly. My code is similar to the example of redux-toolkit.
const postsApiSlice = api.injectEndpoints({
endpoints: (builder) => ({
getPost: builder.query<Post, number>({
query: (id) => ROUTES.POST(id),
providesTags: (result, error, id) => {
return [{ type: POST_TAG, id }]
},
}),
updatePostWithOptimism: builder.mutation<void, Pick<Post, 'id'> & Partial<Post>>({
query: ({ id, ...patch }) => ({
url: ROUTES.POST(id),
method: 'PATCH',
body: patch,
}),
async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {
// ERROR at 'getPost': Argument of type 'string' is not assignable to parameter of type 'never'.ts(2345)
const manualGetPostUpdate = dispatch(api.util.updateQueryData('getPost', id, (draft) => {
Object.assign(draft, patch)
}))
try {
await queryFulfilled
} catch {
manualGetPostUpdate.undo()
}
},
}),
}),
})
CodePudding user response:
The type of api
does not know about the getPost
endpoint. Use the injected api (postsApiSlice.util.updateQueryData
) instead.
Also, on a sidenote: your api naming kinda indicates (I could be wrong) that you are adding that "injected" api into the configureStore
call too as it's own slice. You don't need to do that - just adding api
in configureStore
is enough.