Vilian
Vilian3mo ago

How to query with async/await

I'm trying to initialise my react context store on mount with data coming from trpc. I'm using the t3 stack right now, and it's not immediately obvious on how to wait for the data to load before setting it in the store.. I'm using zustand and he is a snippet of my code
export const defaultInitState: State = {
user: null,
session: null,
permissions: {
user: false,
admin: false
},
tenants: [],
users: null
};

// Store
export const createUserStore = (initState: State = defaultInitState) => {
return createStore<Store>()((set) => ({
...initState,
reloadUsers: async () => {
const query = api.users.all.useQuery();
/// wait for query to be loaded and set the store's user data to the query data
},
reloadTenants: async () => {},

reset: async () => {
set(defaultInitState);

}
}));
};
export const defaultInitState: State = {
user: null,
session: null,
permissions: {
user: false,
admin: false
},
tenants: [],
users: null
};

// Store
export const createUserStore = (initState: State = defaultInitState) => {
return createStore<Store>()((set) => ({
...initState,
reloadUsers: async () => {
const query = api.users.all.useQuery();
/// wait for query to be loaded and set the store's user data to the query data
},
reloadTenants: async () => {},

reset: async () => {
set(defaultInitState);

}
}));
};
3 Replies
Vilian
Vilian3mo ago
I take it that you aren't actually supposed to use the query client like that outside of component So what would be the next prefered method ?
artistrea
artistrea3mo ago
Why would you use zustand when react query already caches data, dedupes requests and has primitives to interact with the data? I'm not sure if I didn't understand some requirement, but I would do something like this:
// since react query shares data globally, this hook works like a store
export function useSomeData() {
const usersQuery = api.users.all.useQuery();

const reloadUsers = api.users.all.refetch;

return {
users: usersQuery.data,
reloadUsers,
reset: async () => {
api.users.all.setQueryData(null);
api.users.all.invalidateQuery();
// ...
}
}
}
// since react query shares data globally, this hook works like a store
export function useSomeData() {
const usersQuery = api.users.all.useQuery();

const reloadUsers = api.users.all.refetch;

return {
users: usersQuery.data,
reloadUsers,
reset: async () => {
api.users.all.setQueryData(null);
api.users.all.invalidateQuery();
// ...
}
}
}
I'm actually not sure what is the syntax for some of the code above, so it may not work out of the box And if you really need to use zustand with react query this way, I think you will need to use mutations
Vilian
Vilian3mo ago
This looks interesting I haven't really thought about doing it like this I'll try this