SansPapyrus683
SansPapyrus6835mo ago

is there a better way to do this?

let query;
let params;
switch (getWhat) {
case "posts":
query = api.user.userPosts;
params = { user: uid, what: "posts", cursor: at };
break;
case "likes":
query = api.user.userPosts;
params = { user: uid, what: "likes", cursor: at };
break;
case "following":
query = api.user.followedPosts;
}

//@ts-ignore
const { data, isPlaceholderData } = query.useQuery(params, {
//@ts-ignore
placeholderData: (prevRes) => prevRes ?? initPosts,
});
let query;
let params;
switch (getWhat) {
case "posts":
query = api.user.userPosts;
params = { user: uid, what: "posts", cursor: at };
break;
case "likes":
query = api.user.userPosts;
params = { user: uid, what: "likes", cursor: at };
break;
case "following":
query = api.user.followedPosts;
}

//@ts-ignore
const { data, isPlaceholderData } = query.useQuery(params, {
//@ts-ignore
placeholderData: (prevRes) => prevRes ?? initPosts,
});
so i have a component that renders a post list according to varying api calls however, this requires the two ts-ignore at the bottom. is there a way to tell ts that the two api calls result in the exact same type?
1 Reply
WeezyEzo
WeezyEzo5mo ago
your implementation is against the laws of hooks. Hooks should not be called conditionally. Instead, you can make use of the enabled option of react query. I think this is the good way of doing what you want.
const { data: posts, isPlaceholderData: isPlaceholderPosts } = api.user.userPosts.useQuery({
user: uid, what: getWhat as 'posts' | 'likes', cursor: at
}, {
enabled: getWhat === 'posts' || getWhat === 'likes',
placeholderData: (prevRes) => prevRest ?? initPosts
})

const { data: following, isPlaceholderData: isPlaceholderFollowing } = api.user.followedPosts.useQuery(undefined, {
enabled: getWhat === 'following',
placeholderData: (prevRes) => prevRest ?? initPosts
})
const { data: posts, isPlaceholderData: isPlaceholderPosts } = api.user.userPosts.useQuery({
user: uid, what: getWhat as 'posts' | 'likes', cursor: at
}, {
enabled: getWhat === 'posts' || getWhat === 'likes',
placeholderData: (prevRes) => prevRest ?? initPosts
})

const { data: following, isPlaceholderData: isPlaceholderFollowing } = api.user.followedPosts.useQuery(undefined, {
enabled: getWhat === 'following',
placeholderData: (prevRes) => prevRest ?? initPosts
})
If you want to use only one variable for any of the data you can do this:
const data = posts || following
const isPlaceholderData = isPlaceholderPosts || isPlaceholderFollowing
const data = posts || following
const isPlaceholderData = isPlaceholderPosts || isPlaceholderFollowing
This issue is more of react-query related rather than trpc.