最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - RTK Query Pattern for fetching data with query arguments - Stack Overflow

programmeradmin0浏览0评论

I have an application where multiple ponents are fetching data like below and is using the data for some rendering.

const {data} = useGetUserQuery({shippingAddressId: 123});

I'm trying to figure out what is the normal RTK query pattern if I wanted to call useGetUserQuery with a new shippingAddressId and have all the ponents consuming this hook rerender?

Since RTK Query uses the query parameters as cache keys, the data doesn't update since the shippingAddressId is hardcoded.

I'm currently getting around this by dispatching an action to the redux store which updates a params object with say shippingAddressId and using that as my query argument in the useGetUserQuery({...params}) hook.

By dispatching an action, all my ponents that are consuming the useGetUserQuery hook gets updated.

Is this an anti-pattern?

Thank you and I look forward to any remendations.

I have an application where multiple ponents are fetching data like below and is using the data for some rendering.

const {data} = useGetUserQuery({shippingAddressId: 123});

I'm trying to figure out what is the normal RTK query pattern if I wanted to call useGetUserQuery with a new shippingAddressId and have all the ponents consuming this hook rerender?

Since RTK Query uses the query parameters as cache keys, the data doesn't update since the shippingAddressId is hardcoded.

I'm currently getting around this by dispatching an action to the redux store which updates a params object with say shippingAddressId and using that as my query argument in the useGetUserQuery({...params}) hook.

By dispatching an action, all my ponents that are consuming the useGetUserQuery hook gets updated.

Is this an anti-pattern?

Thank you and I look forward to any remendations.

Share Improve this question asked Jul 19, 2022 at 6:57 TomPutsTomPuts 1192 silver badges9 bronze badges 1
  • 1 That's perfectly fine. – phry Commented Jul 19, 2022 at 7:24
Add a ment  | 

1 Answer 1

Reset to default 4

As you can read from the redux toolkit query documentation:

RTK Query will automatically fetch data on mount, re-fetch when parameters change, provide {data, isFetching} values in the result, and re-render the ponent as those values change.

So yes, that's how RTKQuery handles the update and the re-fetch, you should use a variable instead of a hardcoded number.

发布评论

评论列表(0)

  1. 暂无评论