T
TanStack3y ago
rare-sapphire

life cycle timing problem with useQuery

My application needs to load general config data via an ajax request. This config contains things like BASE_URL, STALE_TIME and other constants. When I initialize my useQuery, I need these constants to set up the request. Here's a code snippet to help understanding the problem: const store = useStore(); onBeforeMount(async ()=>{ const response = await fetch('./config.json'); const json = await response.json(); store.config.value = json; }); const { data } = useRecordQuery(store.config.value); When I initialize the useRecordQuery, the store.config will be undefined. How do you solve this timing issue. I can't put the useRecordQuery in the lifecycle hook.
6 Replies
correct-apricot
correct-apricot3y ago
I think the simplest way to do that would be to pass enabled: computed(() => Boolean(store.config.value)) to your query. So it will run only after settings are already there. Other way would be to fetch those settings before you render a component that needs it (ex. via suspense).
rare-sapphire
rare-sapphireOP3y ago
Can you, please, elaborate more on the computed solution? I like that. Is enabled an option in the useQuery?
rare-sapphire
rare-sapphireOP3y ago
I found the relevant documentation:
No description
rare-sapphire
rare-sapphireOP3y ago
Thank you, I'll give it a try I tried the computed solution. It did not work for me. The useQuery is only called when the config is undefined. It's not called when the config value changes.
correct-apricot
correct-apricot3y ago
Make sure to NOT unwrap reactive value when passing it to vue-query. Ex. Do not do this useRecordQuery(store.config.value) cause you are loosing reactivity on the prop. vue-query will unwrap ref internally.
rare-sapphire
rare-sapphireOP3y ago
I settled for this solution: 1. loaded config.json in main.js before everything else and pushed it into a Pinia store. 2. used the config.json directly in my useRecordQuery() function, this way the config.json was already loaded.

Did you find this page helpful?