Сначала устанавливаем основные зависимости:
npm install @apollo/client graphql
# или
yarn add @apollo/client graphql
Создаем экземпляр ApolloClient в отдельном файле (обычно apollo-client.js
):
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client';
const httpLink = new HttpLink({
uri: 'https://your-graphql-endpoint.com/graphql', // URL вашего GraphQL API
});
const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
// Дополнительные настройки:
defaultOptions: {
watchQuery: {
fetchPolicy: 'cache-first', // стратегия получения данных по умолчанию
},
},
});
export default client;
Оборачиваем приложение в ApolloProvider (аналогично Redux Provider):
import React from 'react';
import ReactDOM from 'react-dom';
import { ApolloProvider } from '@apollo/client';
import client from './apollo-client';
import App from './App';
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('root')
);
Для работы с авторизацией добавляем middleware для заголовков:
import { ApolloClient, InMemoryCache, HttpLink, from } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';
const httpLink = new HttpLink({ uri: 'https://api.example.com/graphql' });
const authLink = setContext((_, { headers }) => {
const token = localStorage.getItem('authToken');
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : "",
}
};
});
const client = new ApolloClient({
link: from([authLink, httpLink]),
cache: new InMemoryCache()
});
Можно кастомизировать InMemoryCache:
const cache = new InMemoryCache({
typePolicies: {
Product: {
keyFields: ["id", "sku"] // кастомные ключи для нормализации
}
}
});
Для работы с подписками:
import { split, HttpLink, ApolloClient } from '@apollo/client';
import { WebSocketLink } from '@apollo/client/link/ws';
import { getMainDefinition } from '@apollo/client/utilities';
const wsLink = new WebSocketLink({
uri: 'wss://your-graphql-endpoint.com/subscriptions',
options: {
reconnect: true
}
});
const splitLink = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
httpLink
);
Пример запроса данных в функциональном компоненте:
import { useQuery, gql } from '@apollo/client';
const GET_USERS = gql`
query GetUsers {
users {
id
name
email
}
}
`;
function UsersList() {
const { loading, error, data } = useQuery(GET_USERS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ul>
{data.users.map(user => (
<li key={user.id}>{user.name} - {user.email}</li>
))}
</ul>
);
}
const { error } = useQuery(MY_QUERY);
useEffect(() => {
if (error) console.error('GraphQL Error:', error);
}, [error]);
настройка Apollo Client включает создание клиента с указанием endpoint'а, настройку кэша, интеграцию с React через Provider и добавление необходимых middleware. Для production-проектов важно также настроить обработку ошибок и, при необходимости, real-time обновления через WebSocket.