Skip to content

RTK Query - Cache invalidation after HTTP Delete causes 404 #1672

@fvkramer

Description

@fvkramer

I have the following example api slice:

const postService = apiService.injectEndpoints({
  endpoints: (builder) => ({
    fetchPosts: builder.query({
      query: () => `/posts`,
      providesTags: (result = [], error, arg) => [
        "Posts",
        ...result.map(({ id }) => ({ type: "Posts", id })) 
      ],  
    }), 
    getPost: builder.query({
      query: post => `/posts/${post.id}`,
      providesTags: (result, error, arg) => [{ type: "Posts", id: post.id }]
    }), 
    addPost: builder.mutation({
      query: (data) => ({
        url: `/posts`,
        method: "POST",
        body: data.payload
      }), 
      invalidatesTags: [SHIFTS]
    }), 
    updatePost: builder.mutation({
      query: (post) => ({
        url: `/posts/${post.id}`,
        method: "PATCH",
        body: post
      }), 
      invalidatesTags: (result, error, arg) => [{ type: "Posts", id: post.id }]
    }), 
    deletePost: builder.mutation({
      query: (post) => ({
        url: `"/posts/${post.id}`,
        method: "DELETE"
      }), 
      invalidatesTags: (result, error, arg) => [{ type: "Posts", id: post.id }]
    }), 
  }), 
  overrideExisting: false,
})

If a user views a post, the useGetPostQuery hook is run and the post is fetched with tag { type: "Posts", id: post.id }.
Immediately after, if a user deletes the same post, this invalidates the cache for posts and the specific /posts/${post.id} GET, causing a refetch of the /posts/${post.id} resource which 404s because the resource no longer
exists.

  1. GET /posts/1
  2. DELETE /posts/1
  3. RTK Query -> GET /posts/1 -> 404

Is there a way to prevent this? I still need the delete to invalidate the fetchAll cache so users can see updates on screen when deleting.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions