Easy
Composición con fragments
Traducción al español en progresoEl contenido detallado de esta lección aún se está traduciendo. Mientras tanto, se muestra en inglés.
The component below has two separate queries that fetch user data. Both queries select the exact same set of fields on the User type, leading to duplicated field selections. Your task: 1. Extract the common User fields into a GraphQL fragment. 2. Use the fragment spread syntax (...FragmentName) in both queries. 3. Keep the queries working exactly as before, but DRY. Duplicated fields: id, name, email, avatar, role
Código del Problema
import React from 'react';import { useQuery, gql } from '@apollo/client';// Bug: duplicated field selections in both queriesconst GET_CURRENT_USER = gql`query GetCurrentUser {currentUser {idnameavatarrole}}`;const GET_USER_BY_ID = gql`query GetUserById($userId: ID!) {user(id: $userId) {idnameavatarrole}}`;const UserProfile = ({ userId }: { userId?: string }) => {const currentUserResult = useQuery(GET_CURRENT_USER);const specificUserResult = useQuery(GET_USER_BY_ID, {variables: { userId },skip: !userId,});const user = userId ? specificUserResult.data?.user : currentUserResult.data?.currentUser;if (!user) return <p>Loading user...</p>;return (<div><img src={user.avatar} alt={user.name} /><h2>{user.name}</h2><p>{user.email}</p><span>{user.role}</span></div>);};export default UserProfile;
App.tsx