RTK Query 只在变更“成功”后失效标签。

huangapple go评论80阅读模式
英文:

RTK Query invalidateTags only after mutation "success"

问题

Hello, I understand that you want a translation of the provided code. Here's the translated code:

你好,我正在使用RTK Query进行API交互,但我遇到了一些错误,当我触发变异端点时,无论是错误还是成功,都会执行使其失效。

我要寻找的是在变异成功时使标签失效,以下是我的代码:

获取端点

```javascript
getPosts: builder.query({
  query: () => `/posts`,
  providesTags: ['Posts'],
  transformResponse: (response, meta, arg) => response.data,
  transformErrorResponse: (response, meta, arg) => response.data?.message ?? response,
})

变异端点

mutatePost: builder.mutation({
  query: (data, id) => ({
    url: id ? `/posts/${id}` : `/posts`,
    method: id ? 'PATCH' : 'POST',
    body: data,
  }),

  transformResponse: (response, meta, arg) => response.data,
  transformErrorResponse: (response, meta, arg) => response.data?.message ?? response,
  invalidatesTags: ['Posts'],
})

我尝试了所有可用的结果,但都不符合我的期望。


Please let me know if you need any further assistance.

<details>
<summary>英文:</summary>

Hello am using RTK query for API interaction  but am facing some error, where I trigger mutation endpoint invalidation always executed if its error or success.

what i am searching for is Invalidate Tags on mutation success here is my code

Get Endpoints

`getPosts: builder.query({
      query: () =&gt; `/posts`,
      providesTags: [&#39;Posts&#39;],
      transformResponse: (response, meta, arg) =&gt; response.data,
      transformErrorResponse: (response, meta, arg) =&gt;  response.data?.message ?? response ,
    })`

mutation endpoint

` mutatePost: builder.mutation({   
      query: (data,id) =&gt; ({
        url: id?`/posts/${id}`: `/posts`,
        method: id?&#39;PATCH&#39;:&#39;POST&#39;,
        body: data,
      }),
    
      transformResponse: (response, meta, arg) =&gt; response.data,
      transformErrorResponse: (response, meta, arg) =&gt; response.data?.message ?? response , 
      invalidatesTags: [&#39;Posts&#39;],

    })`

i tried all results available but not fit for my expection

</details>


# 答案1
**得分**: 11

你可以使用回调符号
```js
invalidatesTags: (result, error) =&gt; error ? [] : ['Posts'],
英文:

You can use the callback notation

invalidatesTags: (result, error) =&gt; error ? [] : [&#39;Posts&#39;],

huangapple
  • 本文由 发表于 2023年4月7日 00:37:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75951829.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定