useQuery in combination with a Pinia store and store data (Nuxt) #131
-
I have a user store, which holds interface UserStore {
id: number | null
name: string | null
email: string | null
firstName: string | null
lastName: string | null
}
export const useUserStore = defineStore('user', () => {
const state = reactive<UserStore>({
id: null,
name: null,
email: null,
firstName: null,
lastName: null,
})
function setUser(id: number, name: string, email: string, firstName: string, lastName: string) {
state.id = id
state.name = name
state.email = email
state.firstName = firstName
state.lastName = lastName
}
const fullName = computed(() => `${state.firstName} ${state.lastName}`)
return {
setUser,
fullName,
...toRefs(state),
}
}) And a query: export const useUser = defineQuery(() => {
const requestFetch = useRequestFetch()
const { state, ...rest } = useQuery({
key: () => ['user'],
query: () =>
requestFetch('/api/user'),
})
return {
...rest,
user: state,
}
}) So when I run the query at some place const { state } = useUser()
console.log(state.data) // should give me the current user from the backend But what is the right place to update the user in the store, with the user from the query. Or should I just call the useUser query again where I need them? |
Beta Was this translation helpful? Give feedback.
Answered by
posva
Dec 12, 2024
Replies: 1 comment 2 replies
-
I would call |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
posva
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would call
useUser()
where you need to. Since it's a query, it can be invalidated when logging out and it can be awaited when needed with therefresh()
method since it dedupes requests.