3

I have an application where multiple components 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 components 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 components that are consuming the useGetUserQuery hook gets updated.

Is this an anti-pattern?

Thank you and I look forward to any recommendations.

1
  • 1
    That's perfectly fine. Commented Jul 19, 2022 at 7:24

1 Answer 1

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 component 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.

Sign up to request clarification or add additional context in comments.

1 Comment

so, if I need to perform a refetch with other parameter i need to use a variable with a useState or something that keeps track of the change of that variable to perform the refetch... In other words... a query management tool with state support needs another kind of state support to perform a change on the parameter, it doesn't make any sense at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.