Kurs JavaScript i React · Moduł 10: Ekosystem i przyszłość React
Apollo Client - kompleksowa integracja GraphQL z React
W tej lekcji6
Centrum dowodzenia pyta serwer GraphQL o użytkowników, ich posty i komentarze. Gdyby każdy komponent sam wołał fetch, te same dane przylatywałyby wielokrotnie, a po edycji posta część ekranów pokazywałaby starą wersję. Apollo Client wysyła zapytania GraphQL, trzyma odpowiedzi w znormalizowanym cache i odświeża komponenty, gdy dane się zmienią. Obsługuje też optymistyczne aktualizacje i subskrypcje.
Instalacja i podstawowa konfiguracja
Apollo Client 4 potrzebuje trzech pakietów: @apollo/client, graphql i rxjs, bo wersja 4 opiera się na obserwablach z RxJS:
npm install @apollo/client graphql rxjs
# Opcjonalnie: subskrypcje przez WebSocket i wysyłanie plików
npm install graphql-ws apollo-upload-clientPrzykłady w tej lekcji używają API Apollo Client 4: klienta, cache i linki importujesz z @apollo/client, a ApolloProvider i hooki, jak useQuery, z @apollo/client/react. W starszych projektach spotkasz API wersji 3, w którym hooki importowało się prosto z @apollo/client, a klient przyjmował opcję uri.
Klient to łańcuch linków, przez które przechodzi każde zapytanie, oraz cache:
// apolloClient.js
import { ApolloClient, ApolloLink, HttpLink, InMemoryCache, CombinedGraphQLErrors, ServerError } from '@apollo/client';
import { SetContextLink } from '@apollo/client/link/context';
import { ErrorLink } from '@apollo/client/link/error';
// Link HTTP do komunikacji z serwerem GraphQL
const httpLink = new HttpLink({
uri: process.env.REACT_APP_GRAPHQL_ENDPOINT || 'http://localhost:4000/graphql',
credentials: 'include' // Dla cookies/session
});
// Link do obsługi autoryzacji
const authLink = new SetContextLink(({ headers }) => {
const token = localStorage.getItem('authToken');
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : '',
'x-api-version': '1.0',
'x-client-name': 'react-app'
}
};
});
// Link do obsługi błędów
const errorLink = new ErrorLink(({ error, operation, forward }) => {
if (CombinedGraphQLErrors.is(error)) {
error.errors.forEach(({ message, locations, path, extensions }) => {
console.error(
`GraphQL error: Message: ${message}, Location: ${JSON.stringify(locations)}, Path: ${path}`
);
// Obsługa specyficznych błędów
if (extensions?.code === 'UNAUTHENTICATED') {
localStorage.removeItem('authToken');
window.location.href = '/login';
}
});
} else if (ServerError.is(error)) {
console.error(`Server error: ${error.statusCode}`);
// Ponów żądanie po błędzie serwera
if (error.statusCode === 500) {
return forward(operation);
}
} else {
console.error(`Network error: ${error}`);
}
});
// Konfiguracja cache
const cache = new InMemoryCache({
typePolicies: {
User: {
fields: {
// Konfiguracja cache dla pól użytkownika
posts: {
merge(existing = [], incoming) {
return [...existing, ...incoming];
}
}
}
},
Post: {
fields: {
comments: {
merge(existing = [], incoming) {
return incoming;
}
}
}
}
}
});
// Główny klient Apollo
const apolloClient = new ApolloClient({
link: ApolloLink.from([errorLink, authLink, httpLink]),
cache,
defaultOptions: {
watchQuery: {
errorPolicy: 'all',
notifyOnNetworkStatusChange: true
},
query: {
errorPolicy: 'all'
}
},
devtools: { enabled: process.env.NODE_ENV === 'development' }
});
export default apolloClient;ApolloLink.from([errorLink, authLink, httpLink]) ustala kolejność: obsługa błędów, nagłówek autoryzacji, wysyłka HTTP. ErrorLink dostaje jeden obiekt error: CombinedGraphQLErrors.is(error) rozpoznaje błędy zwrócone przez GraphQL, a ServerError.is(error) odpowiedź HTTP z kodem błędu. W SetContextLink pierwszym argumentem jest poprzedni kontekst, stąd ({ headers }). InMemoryCache normalizuje odpowiedzi, czyli zapisuje każdy obiekt osobno pod kluczem z __typename i id, więc powtórne zapytanie o te same dane nie trafia do serwera. typePolicies decydują, jak łączyć listy.
Klienta udostępniasz całej aplikacji przez ApolloProvider, podobnie jak context:
// App.js
import React from 'react';
import { ApolloProvider } from '@apollo/client/react';
import apolloClient from './apolloClient';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import Dashboard from './components/Dashboard';
import UserProfile from './components/UserProfile';
function App() {
return (
<ApolloProvider client={apolloClient}>
<Router>
<div className="App">
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path="/profile/:id" element={<UserProfile />} />
</Routes>
</div>
</Router>
</ApolloProvider>
);
}
export default App;Każdy komponent wewnątrz providera korzysta teraz z hooków Apollo i wspólnego cache.
Wykonywanie zapytań (Queries)
useQuery wykonuje zapytanie automatycznie przy renderowaniu i zwraca data, loading oraz error. Zapytanie opisujesz szablonem gql, a zmienne podajesz w opcji variables:
// Definicja zapytania GraphQL
import { gql } from '@apollo/client';
import { useQuery } from '@apollo/client/react';
const GET_USERS = gql`
query GetUsers($limit: Int, $offset: Int) {
users(limit: $limit, offset: $offset) {
id
name
email
avatar
posts {
id
title
createdAt
}
}
}
`;
function UsersList() {
const { data, loading, error, refetch, fetchMore } = useQuery(GET_USERS, {
variables: { limit: 10, offset: 0 },
notifyOnNetworkStatusChange: true,
errorPolicy: 'all'
});
if (loading) return <div className="loading">Ładowanie użytkowników...</div>;
if (error) return <div className="error">Błąd: {error.message}</div>;
const loadMoreUsers = () => {
fetchMore({
variables: {
offset: data.users.length
},
updateQuery: (prev, { fetchMoreResult }) => {
if (!fetchMoreResult) return prev;
return {
...prev,
users: [...prev.users, ...fetchMoreResult.users]
};
}
});
};
return (
<div>
<h2>Lista użytkowników</h2>
<button onClick={() => refetch()}>Odśwież</button>
<div className="users-grid">
{data.users.map(user => (
<div key={user.id} className="user-card">
<img src={user.avatar} alt={user.name} />
<h3>{user.name}</h3>
<p>{user.email}</p>
<p>Posty: {user.posts.length}</p>
</div>
))}
</div>
<button onClick={loadMoreUsers}>Załaduj więcej</button>
</div>
);
}Kolejność ma znaczenie: najpierw sprawdzasz loading, potem error, a dopiero na końcu renderujesz data. fetchMore dociąga kolejną stronę, a updateQuery dokleja nowych użytkowników do poprzednich.
Zapytania na żądanie
Wyszukiwarka powinna pytać serwer dopiero po kliknięciu. useLazyQuery zwraca funkcję, która uruchamia zapytanie na żądanie:
import { gql } from '@apollo/client';
import { useLazyQuery } from '@apollo/client/react';
import { useState } from 'react';
const SEARCH_USERS = gql`
query SearchUsers($query: String!) {
searchUsers(query: $query) {
id
name
email
avatar
}
}
`;
function UserSearch() {
const [searchTerm, setSearchTerm] = useState('');
const [searchUsers, { data, loading, error }] = useLazyQuery(SEARCH_USERS);
const handleSearch = (e) => {
e.preventDefault();
if (searchTerm.trim()) {
searchUsers({
variables: { query: searchTerm }
});
}
};
return (
<div>
<form onSubmit={handleSearch}>
<input
type="text"
value={searchTerm}
onChange={(e) => setSearchTerm(e.target.value)}
/>
<button type="submit">Szukaj</button>
</form>
{loading && <div>Wyszukiwanie...</div>}
{error && <div>Błąd wyszukiwania: {error.message}</div>}
{data?.searchUsers && (
<div>
<h3>Wyniki wyszukiwania:</h3>
{data.searchUsers.map(user => (
<div key={user.id}>{user.name} - {user.email}</div>
))}
</div>
)}
</div>
);
}searchUsers wywołujesz w handleSearch, a stany loading i error działają jak w useQuery.
Mutacje (Mutations)
Mutacja zmienia dane na serwerze. W przeciwieństwie do useQuery, hook useMutation niczego nie wysyła sam, tylko zwraca funkcję, którą wywołujesz na żądanie, np. w onSubmit:
import { gql } from '@apollo/client';
import { useMutation } from '@apollo/client/react';
import { useState } from 'react';
const CREATE_POST = gql`
mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) {
id
title
content
author {
id
name
}
createdAt
}
}
`;
const GET_POSTS = gql`
query GetPosts {
posts {
id
title
content
author {
id
name
}
createdAt
}
}
`;
function CreatePostForm() {
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [createPost, { loading, error }] = useMutation(CREATE_POST, {
// Aktualizacja cache po utworzeniu posta
update(cache, { data: { createPost } }) {
const existingPosts = cache.readQuery({ query: GET_POSTS });
cache.writeQuery({
query: GET_POSTS,
data: {
posts: [createPost, ...existingPosts.posts]
}
});
},
// Optymistyczna aktualizacja
optimisticResponse: {
createPost: {
__typename: 'Post',
id: 'temp-id',
title,
content,
author: {
__typename: 'User',
id: 'current-user-id',
name: 'Ty'
},
createdAt: new Date().toISOString()
}
},
// Obsługa błędów
onError: (error) => {
console.error('Błąd tworzenia posta:', error);
},
onCompleted: (data) => {
console.log('Post został utworzony:', data.createPost);
setTitle('');
setContent('');
}
});
const handleSubmit = async (e) => {
e.preventDefault();
if (!title.trim() || !content.trim()) {
alert('Wypełnij wszystkie pola');
return;
}
try {
await createPost({
variables: {
input: { title, content }
}
});
} catch (err) {
console.error('Błąd podczas tworzenia posta:', err);
}
};
return (
<form onSubmit={handleSubmit}>
<div>
<label>Tytuł:</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
disabled={loading}
/>
</div>
<div>
<label>Treść:</label>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
disabled={loading}
/>
</div>
<button type="submit" disabled={loading}>
{loading ? 'Tworzenie...' : 'Utwórz post'}
</button>
{error && <div className="error">Błąd: {error.message}</div>}
</form>
);
}update dopisuje nowy post do zapytania GET_POSTS w cache, więc lista odświeży się bez pytania serwera. optimisticResponse pokazuje post natychmiast, a gdy mutacja się nie uda, Apollo wycofa tę tymczasową wersję.
Zaawansowane zarządzanie cache
Przy usuwaniu posta cache trzeba posprzątać ręcznie, bo Apollo nie wie, które listy zawierały ten obiekt:
import { gql } from '@apollo/client';
import { useMutation, useQuery } from '@apollo/client/react';
const DELETE_POST = gql`
mutation DeletePost($id: ID!) {
deletePost(id: $id) {
id
}
}
`;
const UPDATE_POST = gql`
mutation UpdatePost($id: ID!, $input: UpdatePostInput!) {
updatePost(id: $id, input: $input) {
id
title
content
updatedAt
}
}
`;
function PostManager({ postId }) {
const [deletePost] = useMutation(DELETE_POST, {
// Usuń z cache po usunięciu
update(cache, { data: { deletePost } }) {
cache.modify({
fields: {
posts(existingPosts = [], { readField }) {
return existingPosts.filter(
postRef => deletePost.id !== readField('id', postRef)
);
}
}
});
// Usuń też z cache poszczególny post
cache.evict({ id: cache.identify({ __typename: 'Post', id: deletePost.id }) });
cache.gc();
}
});
const [updatePost] = useMutation(UPDATE_POST, {
// Nie potrzebujemy update - Apollo automatycznie zaktualizuje cache
// jeśli zwrócone dane mają to samo ID i __typename
});
const handleDelete = async () => {
if (window.confirm('Czy na pewno chcesz usunąć ten post?')) {
try {
await deletePost({
variables: { id: postId }
});
} catch (error) {
console.error('Błąd usuwania posta:', error);
}
}
};
const handleUpdate = async (newTitle, newContent) => {
try {
await updatePost({
variables: {
id: postId,
input: { title: newTitle, content: newContent }
}
});
} catch (error) {
console.error('Błąd aktualizacji posta:', error);
}
};
return (
<div>
<button onClick={handleDelete}>Usuń post</button>
{/* Formularz edycji */}
</div>
);
}cache.modify wycina referencję z listy posts, a evict i gc usuwają sam obiekt. Przy aktualizacji nic nie musisz robić: odpowiedź z tym samym id i __typename sama nadpisze obiekt w cache.
Subskrypcje (Subscriptions)
Subskrypcje przesyłają dane w czasie rzeczywistym przez WebSocket. ApolloLink.split kieruje je do GraphQLWsLink, a zapytania i mutacje do HTTP:
// apolloClient.js - rozszerzenie konfiguracji
import { OperationTypeNode } from 'graphql';
import { ApolloLink } from '@apollo/client';
import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { createClient } from 'graphql-ws';
// WebSocket link dla subskrypcji
const wsLink = new GraphQLWsLink(
createClient({
url: process.env.REACT_APP_GRAPHQL_WS_ENDPOINT || 'ws://localhost:4000/graphql',
connectionParams: () => {
const token = localStorage.getItem('authToken');
return {
authorization: token ? `Bearer ${token}` : ''
};
},
on: {
connected: () => console.log('WebSocket connected'),
closed: () => console.log('WebSocket disconnected')
}
})
);
// Podział ruchu - HTTP dla queries/mutations, WebSocket dla subscriptions
const splitLink = ApolloLink.split(
({ operationType }) => operationType === OperationTypeNode.SUBSCRIPTION,
wsLink,
ApolloLink.from([errorLink, authLink, httpLink])
);
// Aktualizacja klienta
const apolloClient = new ApolloClient({
link: splitLink, // Użyj splitLink zamiast ApolloLink.from([...])
cache,
// ... reszta konfiguracji
});W wersji 4 operacja ma pole operationType, więc test porównuje je z OperationTypeNode.SUBSCRIPTION z pakietu graphql. Pakiet graphql-ws to następca nieutrzymywanego subscriptions-transport-ws, więc wybieraj właśnie jego.
Komponent nasłuchuje zdarzeń hookiem useSubscription i dopisuje nowe posty do cache:
import { gql } from '@apollo/client';
import { useSubscription, useQuery } from '@apollo/client/react';
const POST_ADDED_SUBSCRIPTION = gql`
subscription PostAdded {
postAdded {
id
title
content
author {
id
name
}
createdAt
}
}
`;
const COMMENT_ADDED_SUBSCRIPTION = gql`
subscription CommentAdded($postId: ID!) {
commentAdded(postId: $postId) {
id
content
author {
id
name
}
createdAt
}
}
`;
function LivePostsFeed() {
const { data: postsData, loading } = useQuery(GET_POSTS);
// Subskrypcja na nowe posty
useSubscription(POST_ADDED_SUBSCRIPTION, {
onData: ({ data, client }) => {
const newPost = data.data.postAdded;
// Aktualizuj cache
const existingPosts = client.readQuery({ query: GET_POSTS });
client.writeQuery({
query: GET_POSTS,
data: {
posts: [newPost, ...existingPosts.posts]
}
});
// Pokazanie notyfikacji
showNotification(`Nowy post: ${newPost.title}`);
}
});
if (loading) return <div>Ładowanie...</div>;
return (
<div>
<h2>Na żywo - posty</h2>
{postsData?.posts.map(post => (
<LivePostCard key={post.id} post={post} />
))}
</div>
);
}
function LivePostCard({ post }) {
// Subskrypcja na nowe komentarze dla tego posta
useSubscription(COMMENT_ADDED_SUBSCRIPTION, {
variables: { postId: post.id },
onData: ({ data }) => {
const newComment = data.data.commentAdded;
console.log(`Nowy komentarz w poście ${post.title}:`, newComment.content);
}
});
return (
<div className="post-card">
<h3>{post.title}</h3>
<p>{post.content}</p>
<small>Autor: {post.author.name}</small>
</div>
);
}onData dostaje klienta i wynik subskrypcji, więc nowy post leży w data.data.postAdded. Starszą nazwę onSubscriptionData Apollo Client 4 usunął, więc taki callback już się nie wywoła.
Zaawansowane wzorce
Fragment to wielokrotnego użytku zestaw pól. USER_FRAGMENT definiujesz raz i wklejasz w każde zapytanie o użytkownika:
// fragments.js
import { gql } from '@apollo/client';
export const USER_FRAGMENT = gql`
fragment UserInfo on User {
id
name
email
avatar
}
`;
export const POST_FRAGMENT = gql`
fragment PostInfo on Post {
id
title
content
createdAt
author {
...UserInfo
}
}
${USER_FRAGMENT}
`;
// Użycie fragmentów
const GET_POSTS_WITH_FRAGMENTS = gql`
query GetPosts {
posts {
...PostInfo
}
}
${POST_FRAGMENT}
`;Zmiana pól we fragmencie aktualizuje wszystkie zapytania, które go używają, a ${USER_FRAGMENT} dołącza jego definicję do dokumentu.
usePostOperations zamyka zapytanie, mutację i paginację w jednym hooku, więc komponent strony widzi proste API:
// hooks/usePostOperations.js
import { gql } from '@apollo/client';
import { useQuery, useMutation } from '@apollo/client/react';
import { POST_FRAGMENT } from '../fragments';
const GET_POSTS = gql`
query GetPosts($limit: Int, $offset: Int) {
posts(limit: $limit, offset: $offset) {
...PostInfo
}
}
${POST_FRAGMENT}
`;
const CREATE_POST = gql`
mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) {
...PostInfo
}
}
${POST_FRAGMENT}
`;
export function usePostOperations() {
const { data, loading, error, refetch, fetchMore } = useQuery(GET_POSTS, {
variables: { limit: 10, offset: 0 }
});
const [createPostMutation, { loading: creating }] = useMutation(CREATE_POST, {
update(cache, { data: { createPost } }) {
const existingPosts = cache.readQuery({ query: GET_POSTS });
cache.writeQuery({
query: GET_POSTS,
data: {
posts: [createPost, ...existingPosts.posts]
}
});
}
});
const createPost = async (postData) => {
try {
const result = await createPostMutation({
variables: { input: postData }
});
return { success: true, post: result.data.createPost };
} catch (error) {
return { success: false, error: error.message };
}
};
const loadMore = () => {
return fetchMore({
variables: { offset: data?.posts?.length || 0 },
updateQuery: (prev, { fetchMoreResult }) => ({
...prev,
posts: [...prev.posts, ...fetchMoreResult.posts]
})
});
};
return {
posts: data?.posts || [],
loading,
error,
creating,
createPost,
refetch,
loadMore
};
}
// Użycie custom hook
function PostsPage() {
const { posts, loading, createPost, loadMore } = usePostOperations();
const handleCreatePost = async (formData) => {
const result = await createPost(formData);
if (result.success) {
console.log('Post created successfully');
} else {
console.error('Failed to create post:', result.error);
}
};
return (
<div>
<CreatePostForm onSubmit={handleCreatePost} />
{loading ? (
<div>Loading...</div>
) : (
<PostsList posts={posts} onLoadMore={loadMore} />
)}
</div>
);
}PostsPage nie wie nic o GraphQL. Gdy zmienisz schemat, poprawiasz jeden hook zamiast dziesięciu komponentów, i taki podział polecam.
GraphQLErrorBoundary łapie błąd renderowania i pokazuje ekran awaryjny z przyciskiem ponowienia, zamiast wywracać całe drzewo:
import React from 'react';
import { CombinedGraphQLErrors, ServerError } from '@apollo/client';
import { ApolloProvider } from '@apollo/client/react';
class GraphQLErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
if (CombinedGraphQLErrors.is(error)) {
console.error('GraphQL Error:', error.errors);
} else if (ServerError.is(error)) {
console.error('Server Error:', error.statusCode);
}
// Wyślij błąd do systemu monitorowania
this.logErrorToService(error, errorInfo);
}
logErrorToService(error, errorInfo) {
// Integracja z Sentry, LogRocket, etc.
console.error('Error logged:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return (
<div className="error-boundary">
<h2>Coś poszło nie tak z GraphQL</h2>
<details>
<summary>Szczegóły błędu</summary>
<pre>{this.state.error?.message}</pre>
</details>
<button onClick={() => this.setState({ hasError: false, error: null })}>
Spróbuj ponownie
</button>
</div>
);
}
return this.props.children;
}
}
// Użycie
function App() {
return (
<ApolloProvider client={apolloClient}>
<GraphQLErrorBoundary>
<Router>
{/* Twoja aplikacja */}
</Router>
</GraphQLErrorBoundary>
</ApolloProvider>
);
}Apollo Client 4 nie ma już klasy ApolloError z wersji 3: błędy GraphQL rozpoznasz przez CombinedGraphQLErrors.is(error) (lista w error.errors), a odpowiedź HTTP z kodem błędu przez ServerError.is(error). Do granicy błędów trafią np. z useSuspenseQuery, bo useQuery nie rzuca błędu, tylko zwraca go w polu error.
Do testów służy MockedProvider, który zamiast serwera zwraca przygotowane odpowiedzi:
// __tests__/UsersList.test.js
import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import { MockedProvider } from '@apollo/client/testing/react';
import UsersList, { GET_USERS } from '../UsersList';
const mocks = [
{
request: {
query: GET_USERS,
variables: { limit: 10, offset: 0 }
},
result: {
data: {
users: [
{
__typename: 'User',
id: '1',
name: 'John Doe',
email: 'john@example.com',
avatar: 'https://example.com/avatar1.jpg',
posts: []
}
]
}
}
}
];
test('renders users list', async () => {
render(
<MockedProvider mocks={mocks}>
<UsersList />
</MockedProvider>
);
// Sprawdź loading state
expect(screen.getByText('Ładowanie użytkowników...')).toBeInTheDocument();
// Poczekaj na załadowanie danych
await waitFor(() => {
expect(screen.getByText('John Doe')).toBeInTheDocument();
});
});
test('handles error state', async () => {
const errorMocks = [
{
request: {
query: GET_USERS,
variables: { limit: 10, offset: 0 }
},
error: new Error('Network error')
}
];
render(
<MockedProvider mocks={errorMocks}>
<UsersList />
</MockedProvider>
);
await waitFor(() => {
expect(screen.getByText(/Błąd: Network error/)).toBeInTheDocument();
});
});Mock musi pasować do zapytania i zmiennych co do joty, inaczej test dostanie błąd. W Apollo Client 4 MockedProvider importujesz z @apollo/client/testing/react, a opcji addTypename już nie ma: cache zawsze dopisuje __typename do zapytań, więc dane mocka też je zawierają i normalizacja działa jak w produkcji. Drugi test sprawdza, czy komunikat błędu trafia na ekran.
Kiedy używać Apollo Client?
Apollo Client sprawdza się, gdy backend używa GraphQL i potrzebujesz cache, który sam normalizuje i deduplikuje dane. Pomaga przy optymistycznych aktualizacjach, na przykład polubienie posta widać od razu, przy danych w czasie rzeczywistym przez subskrypcje, a Apollo DevTools pokazują w przeglądarce cache, zapytania i mutacje. Alternatywy to lżejszy urql z prostszym API, React Query z prostym klientem graphql-request oraz Relay od Mety, zoptymalizowany pod duże aplikacje. React Query, czyli TanStack Query, poznasz w jednej z kolejnych lekcji.
Pamiętaj: Apollo Client to system łączności statku, który nie tylko odbiera sygnały, ale też buforuje je w cache i rozsyła do każdego modułu, który ich potrzebuje.
Kod do tej lekcji: App.jsx
import React, { useState, useEffect } from 'react';
// Symulacja Apollo Client: zapytania, mutacja i znormalizowany cache
// W prawdziwej aplikacji robią to ApolloClient, InMemoryCache, useQuery i useMutation
// Dane po stronie "serwera" GraphQL
let serverMissions = [
{ id: '1', name: 'Nebula Explorer', status: 'ACTIVE', crew: 12, progress: 78 },
{ id: '2', name: 'Dark Matter Probe', status: 'PLANNING', crew: 5, progress: 15 },
{ id: '3', name: 'Solar Flare Watch', status: 'COMPLETED', crew: 8, progress: 100 },
{ id: '4', name: 'Asteroid Mining Delta', status: 'ACTIVE', crew: 20, progress: 45 },
];
const serverCrew = [
{ id: '1', name: 'Komandor Nova', role: 'dowództwo', missionId: '1' },
{ id: '2', name: 'Dr. Stellar', role: 'nauka', missionId: '1' },
{ id: '3', name: 'Astro-7', role: 'technika', missionId: '2' },
{ id: '4', name: 'Ra', role: 'nawigacja', missionId: '4' },
];
const STATUS_LABELS = { ACTIVE: 'Aktywna', PLANNING: 'W planach', COMPLETED: 'Zakończona', SUSPENDED: 'Wstrzymana' };
const STATUS_COLORS = { ACTIVE: '#00ff88', PLANNING: '#ffa500', COMPLETED: '#64ffda', SUSPENDED: '#ff6b6b' };
// Znormalizowany cache jak w InMemoryCache: każdy obiekt leży raz pod kluczem Typ:id,
// a wynik zapytania przechowuje tylko listę kluczy
const cache = { objects: new Map(), queries: new Map() };
function writeQuery(queryName, missions) {
missions.forEach((mission) => cache.objects.set(`Mission:${mission.id}`, mission));
cache.queries.set(queryName, missions.map((mission) => `Mission:${mission.id}`));
}
function readQuery(queryName) {
const refs = cache.queries.get(queryName);
return refs ? refs.map((ref) => cache.objects.get(ref)) : null;
}
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Zapytanie: najpierw cache, a dopiero przy braku danych "sieć"
async function runQuery(queryName, variables = {}) {
if (queryName === 'GET_MISSIONS') {
const cached = readQuery('GET_MISSIONS');
if (cached) return { data: cached, fromCache: true };
await delay(800);
writeQuery('GET_MISSIONS', serverMissions);
return { data: readQuery('GET_MISSIONS'), fromCache: false };
}
if (queryName === 'GET_MISSION_CREW') {
await delay(500);
return { data: serverCrew.filter((member) => member.missionId === variables.id), fromCache: false };
}
throw new Error(`Nieznane zapytanie: ${queryName}`);
}
// Mutacja zmienia dane na serwerze i zwraca obiekt z id, więc cache
// podmienia obiekt Mission:id, a każda lista z tym kluczem widzi nową wersję
async function runMutation(mutationName, variables) {
await delay(500);
if (mutationName !== 'UPDATE_MISSION_STATUS') throw new Error(`Nieznana mutacja: ${mutationName}`);
const mission = serverMissions.find((item) => item.id === variables.id);
if (!mission) throw new Error(`Nie znaleziono misji ${variables.id}`);
const updated = { ...mission, status: variables.status };
serverMissions = serverMissions.map((item) => (item.id === updated.id ? updated : item));
cache.objects.set(`Mission:${updated.id}`, updated);
return { data: { updateMissionStatus: updated } };
}
// Hook symulujący useQuery: zwraca loading, data i error
function useSimulatedQuery(queryName, variables = {}, refreshKey = 0) {
const [state, setState] = useState({ loading: true, data: null, error: null, fromCache: false });
const variablesKey = JSON.stringify(variables);
useEffect(() => {
let ignore = false;
setState((prev) => ({ ...prev, loading: true }));
runQuery(queryName, JSON.parse(variablesKey))
.then((result) => {
if (!ignore) setState({ loading: false, data: result.data, error: null, fromCache: result.fromCache });
})
.catch((error) => {
if (!ignore) setState({ loading: false, data: null, error: error.message, fromCache: false });
});
return () => {
ignore = true;
};
}, [queryName, variablesKey, refreshKey]);
return state;
}
function MissionList({ selectedId, onSelect, refreshKey }) {
const { loading, data, error, fromCache } = useSimulatedQuery('GET_MISSIONS', {}, refreshKey);
if (loading && !data) return <div style={styles.loader}>Wczytywanie danych z serwera GraphQL...</div>;
if (error) return <div style={styles.error}>Błąd: {error}</div>;
return (
<div style={styles.panel}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: '8px' }}>
<h3 style={styles.heading}>Misje kosmiczne</h3>
<span style={fromCache ? styles.cacheBadge : styles.serverBadge}>{fromCache ? 'Z cache' : 'Z serwera'}</span>
</div>
{data.map((mission) => (
<button
key={mission.id}
onClick={() => onSelect(mission.id)}
style={{ ...styles.missionCard, borderColor: mission.id === selectedId ? '#00d4ff' : 'transparent' }}
>
<div style={{ display: 'flex', justifyContent: 'space-between', gap: '8px' }}>
<strong style={{ color: '#e0e1dd' }}>{mission.name}</strong>
<span style={{ color: STATUS_COLORS[mission.status], fontSize: '12px' }}>{STATUS_LABELS[mission.status]}</span>
</div>
<div style={styles.progressBar}>
<div style={{ ...styles.progressFill, width: `${mission.progress}%` }} />
</div>
<span style={{ color: '#8892b0', fontSize: '12px' }}>Załoga: {mission.crew} | Postęp: {mission.progress}%</span>
</button>
))}
</div>
);
}
function MissionCrew({ missionId }) {
const { loading, data } = useSimulatedQuery('GET_MISSION_CREW', { id: missionId });
if (loading) return <p style={styles.muted}>Wczytywanie załogi...</p>;
if (data.length === 0) return <p style={styles.muted}>Brak przypisanej załogi.</p>;
return (
<ul style={{ margin: '0 0 12px', paddingLeft: '18px', color: '#e0e1dd', fontSize: '13px' }}>
{data.map((member) => (
<li key={member.id}>{member.name} - {member.role}</li>
))}
</ul>
);
}
function MutationPanel({ selectedId, onMutated }) {
const [mutating, setMutating] = useState(false);
const [result, setResult] = useState(null);
const [error, setError] = useState(null);
if (!selectedId) {
return (
<div style={styles.panel}>
<h3 style={styles.heading}>Mutacje GraphQL</h3>
<p style={styles.muted}>Wybierz misję z listy, żeby zobaczyć jej załogę i zmienić status.</p>
</div>
);
}
const handleMutation = async (status) => {
setMutating(true);
setError(null);
try {
const { data } = await runMutation('UPDATE_MISSION_STATUS', { id: selectedId, status });
const mission = data.updateMissionStatus;
setResult(`${mission.name}: ${STATUS_LABELS[mission.status]}. Serwer zwrócił obiekt z id, więc cache podmienił Mission:${mission.id}, a lista odczytała go bez nowego zapytania.`);
onMutated();
} catch (err) {
setError(err.message);
} finally {
setMutating(false);
}
};
return (
<div style={styles.panel}>
<h3 style={styles.heading}>Mutacje GraphQL</h3>
<p style={{ ...styles.muted, marginTop: 0 }}>Załoga (zapytanie ze zmienną id):</p>
<MissionCrew missionId={selectedId} />
<p style={{ ...styles.muted, marginTop: 0 }}>Zmień status (mutacja):</p>
<div style={{ display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
{Object.keys(STATUS_LABELS).map((status) => (
<button key={status} onClick={() => handleMutation(status)} disabled={mutating}
style={{ ...styles.btn, opacity: mutating ? 0.5 : 1 }}>
{STATUS_LABELS[status]}
</button>
))}
</div>
{mutating && <p style={styles.muted}>Wysyłanie mutacji...</p>}
{result && !mutating && <p style={{ color: '#00ff88', fontSize: '13px', marginTop: '10px' }}>{result}</p>}
{error && <p style={styles.error}>{error}</p>}
</div>
);
}
function App() {
const [selectedMission, setSelectedMission] = useState(null);
const [refreshKey, setRefreshKey] = useState(0);
return (
<div style={styles.container}>
<h1 style={styles.title}>Apollo Client - centrum dowodzenia GraphQL</h1>
<p style={styles.subtitle}>Symulacja zapytań, mutacji i znormalizowanego cache</p>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(260px, 1fr))', gap: '16px' }}>
<MissionList selectedId={selectedMission} onSelect={setSelectedMission} refreshKey={refreshKey} />
<MutationPanel key={selectedMission} selectedId={selectedMission} onMutated={() => setRefreshKey((key) => key + 1)} />
</div>
<p style={styles.note}>Po mutacji lista pokazuje plakietkę "Z cache": nowy status przyszedł w odpowiedzi mutacji i trafił do cache, więc zapytanie GET_MISSIONS nie musiało pytać serwera. W Apollo Client useQuery odświeżyłby listę sam, bo obserwuje cache.</p>
</div>
);
}
const styles = {
container: { minHeight: '100vh', background: 'linear-gradient(135deg, #0d1b2a 0%, #1a1a3e 100%)', padding: '24px 16px', color: '#e0e1dd', fontFamily: 'system-ui, sans-serif', boxSizing: 'border-box' },
title: { textAlign: 'center', color: '#00d4ff', margin: '0 0 4px', fontSize: '24px' },
subtitle: { textAlign: 'center', color: '#8892b0', marginBottom: '20px' },
panel: { background: 'rgba(0,0,0,0.3)', borderRadius: '12px', padding: '16px', border: '1px solid rgba(0,212,255,0.2)' },
heading: { color: '#00d4ff', margin: '0 0 12px', fontSize: '17px' },
missionCard: { display: 'block', width: '100%', textAlign: 'left', padding: '12px', background: 'rgba(0,0,0,0.3)', borderRadius: '8px', marginBottom: '8px', cursor: 'pointer', border: '1px solid transparent', color: 'inherit', font: 'inherit' },
progressBar: { height: '6px', background: 'rgba(255,255,255,0.1)', borderRadius: '3px', margin: '8px 0' },
progressFill: { height: '100%', background: 'linear-gradient(90deg, #00d4ff, #00ff88)', borderRadius: '3px', transition: 'width 0.3s' },
cacheBadge: { background: '#00ff88', color: '#0d1b2a', padding: '2px 8px', borderRadius: '4px', fontSize: '11px', fontWeight: 'bold', whiteSpace: 'nowrap' },
serverBadge: { background: 'rgba(0,212,255,0.2)', color: '#00d4ff', padding: '2px 8px', borderRadius: '4px', fontSize: '11px', fontWeight: 'bold', whiteSpace: 'nowrap' },
loader: { color: '#8892b0', textAlign: 'center', padding: '40px' },
error: { color: '#ff6b6b', fontSize: '13px' },
muted: { color: '#8892b0', fontSize: '13px' },
btn: { padding: '8px 12px', background: 'rgba(0,212,255,0.15)', border: '1px solid #00d4ff', borderRadius: '6px', color: '#00d4ff', cursor: 'pointer', fontSize: '12px' },
note: { maxWidth: '760px', margin: '16px auto 0', color: '#8892b0', fontSize: '13px', lineHeight: 1.5 },
};
export default App;Hasła z dokumentacji w tej lekcji
Widzisz błąd w tej lekcji?
Sprawdź się
Odpowiedz na pytania z tej lekcji. Wybierz odpowiedź, a od razu zobaczysz, czy jest poprawna.
1. Jaką rolę pełni InMemoryCache w Apollo Client?
2. Czym różni się hook useMutation od useQuery w Apollo Client?
Zadania praktyczne w grze
- Klikanie w kolejności
Kliknij elementy w kolejności z lekcji: wywołanie useQuery, obsługa ładowania (loading), obsługa błędu (error) i wyświetlenie danych:
- Klikanie w kolejności
Ułóż składnię użycia hooka useQuery z Apollo Client:
- Układanie w poziomie
Ułóż elementy wywołania useQuery w Apollo Client od lewej do prawej: