I'm facing an issue with the Favourite Game button component. When a user tries to favorite or unfavorite a game, the icon doesn't update immediately based on the mutation result. Can anyone offer some insights or help me find a solution to this problem? Thank you!
👇 GamePageTop.tsx that will import FavouriteGameButton: receives a gameId prop and checks if there's a logged-in user. If there is, it fetches the user data and extracts the favorite games.
type Props = {
gameId: string;
};
export const GamePageTop: FC<Props> = ({ gameId }) => {
const { user } = useUser();
if (!user) {
return null;
}
const [{ data: userData }] = useUserQuery({
variables: { userId: user.id },
});
const favouriteGame = userData?.user?.favouriteGame.map((it) => it.game.id);
return (
<FavouriteGameButton
gameId={gameId}
isFavourite={favouriteGame?.includes(gameId) || false}
/>
);
};
👇FavouriteGameButton.tsx that receives the gameId and isFavourite prop. Inside the component, it uses the updateFavouriteGameMutation to handle the user's favorite/unfavorite action.
type Props = {
gameId: string;
isFavourite: boolean;
};
export const FavouriteGameButton: FC<Props> = ({ gameId, isFavourite }) => {
const { user } = useUser();
const [, updateFavouriteGame] = useUpdateFavouriteGameMutation();
if (!user) {
return null;
}
const handleUpdateFavouriteGame = async () => {
await updateFavouriteGame({
userId: user.id,
gameId: gameId,
action: isFavourite ? "remove" : "add",
});
};
return (
<ButtonComponent
size={"normal"}
hovercolor="transparent"
backgroundcolor="transparent"
padding="0px"
onClick={() => {
handleUpdateFavouriteGame();
}}
>
{isFavourite ? (
<Icon icon={"starFill"} size="M" color={Colors.TagText} />
) : (
<Icon icon={"starOutline"} size="M" color={Colors.TagText} />
)}
</ButtonComponent>
);
};
You have a couple choices.
useUserQuery
query when your updateFavouriteGame
mutation completes. Refetching is an option of a mutation operation.isFavourite
as state at the level of your GamePageTop
component, pass the setState
function for that state down to the FavouriteGameButton
component, and then update that state when your query completes.