toadmilk
toadmilk2y ago

problem with useContext (likely easy fix)

function userCard(
user: {
id: string;
name: string | null;
image: string | null;
},
id: string,
) {

const toggleFollow = toggleFollowFunc(user.id);

return (
<div className="flex items-center gap-4">
...
<FollowButton
isFollowing={true} //TODO: Fix this
isLoading={toggleFollow.isLoading}
userId={id}
onClick={() => toggleFollow.mutate({userId: id})}
/>
</div>
);
}

export const toggleFollowFunc = (id: string) => {
const trpcUtils = api.useContext();
return api.profile.toggleFollow.useMutation({
onSuccess: ({ addedFollow }) => {
trpcUtils.profile.getById.setData({ id }, (oldData) => {
if (oldData == null) return;

const countModifier = addedFollow ? 1 : -1;
return {
...oldData,
isFollowing: addedFollow,
followersCount: oldData.followersCount + countModifier,
}
})
}
});
}
function userCard(
user: {
id: string;
name: string | null;
image: string | null;
},
id: string,
) {

const toggleFollow = toggleFollowFunc(user.id);

return (
<div className="flex items-center gap-4">
...
<FollowButton
isFollowing={true} //TODO: Fix this
isLoading={toggleFollow.isLoading}
userId={id}
onClick={() => toggleFollow.mutate({userId: id})}
/>
</div>
);
}

export const toggleFollowFunc = (id: string) => {
const trpcUtils = api.useContext();
return api.profile.toggleFollow.useMutation({
onSuccess: ({ addedFollow }) => {
trpcUtils.profile.getById.setData({ id }, (oldData) => {
if (oldData == null) return;

const countModifier = addedFollow ? 1 : -1;
return {
...oldData,
isFollowing: addedFollow,
followersCount: oldData.followersCount + countModifier,
}
})
}
});
}
could someone please explain what im doing wrong thats giving me this error? cheers
2 Replies
toadmilk
toadmilkOP2y ago
it was working before when you could just follow one person on their profile but now that I am trying to add the option to follow their followers as well it breaks
.traevelliath
.traevelliath2y ago
It's actually pretty simple to fix: just move trpcUtils declaration outside of a function. You should probalby get the desired data inside a component and pass it as a prop.