Apollo Client 란?
GraphQL와, 클라이언트를 연결해주는 Node.js 패키지
프론트엔드에서 다뤄지는 여러가지 데이터를 graphql을 사용해 DB에서 가져올 수 있도록 해준다.
Apollo Client 사용법
GraphQL & Apollo Client 설치
npm i graphql @apollo/client
javascript에서 GraphQL 가져오기
// React 프로젝트 내부 .js 파일
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
useQuery,
gql
} from "@apollo/client";
// ApolloClient 불러오기
// uri안에 GraphQL 서버 주소 넣기
// GraphQL 쿼리 결과를 저장하는데 사용할 cache 생성하기
const client = new ApolloClient({
uri: "https://localhost:4000",
cache: new InMemoryCache(),
});
React에서 GraphQL 쿼리 사용하기
client
.query({
query: gql`
query GetRates {
rates(currency: "USD") {
currency
}
}
`
})
.then(result => console.log(result));
React 프로젝트에 GraphQL 연결하기
// React 프로젝트 내부 .js 파일
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
useQuery,
gql
} from "@apollo/client";
// ApolloClient 불러오기
const client = new ApolloClient({
uri: "https://localhost:4000",
cache: new InMemoryCache(),
});
function App() {
return (
<div>
<h2>My first Apollo app 🚀</h2>
</div>
);
}
// ApolloProvider로 GraphQL을 사용할 부분(React App 전체)를 감싸준다.
// apollo client를 통해 GraphQL을 연결해준다.
render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('root'),
);
GraphQL 쿼리(Query) 사용하여, 데이터 가져오기
// 모듈 불러와 작업 준비
import { gql, useQuery } from "@apollo/client";
// GetExchangeRates 쿼리 사용하기 위해 쿼리문 작성해 저장하기
const EXCHANGE_RATES = gql`
query GetExchangeRates {
rates(currency: "USD") {
currency
rate
}
}
`;
// useQuery() 함수로, React 컴포넌트 내부에서 쿼리문 사용하기
function ExchangeRates() {
const { loading, error, data } = useQuery(EXCHANGE_RATES);
// 로딩시에 실행할 내용
if (loading) return <p>Loading...</p>;
// 에러시에 실행할 내용
if (error) return <p>Error :(</p>;
return data.rates.map(({ currency, rate }) => (
<div key={currency}>
<p>
{currency}: {rate}
</p>
</div>
));
}
GraphQL 뮤테이션(Mutation) 사용하여, 데이터 수정하기
// 모듈 불러와 작업 준비
import { gql, useMutation } from "@apollo/client";
// AddTodo 사용하기 위해 뮤테이션 작성해 저장하기
const ADD_TODO = gql`
mutation AddTodo($text: String!) {
addTodo(text: $text) {
id
text
}
}
`;
// useMutation() 함수로, React 컴포넌트 내부에서 뮤테이션 사용하기
function AddTodo() {
let input;
// 뮤테이션을 함수형식으로 불러온다. (addTodo)
const [addTodo, { data, loading, error }] = useMutation(ADD_TODO);
if (loading) return 'Submitting...';
if (error) return `Submission error! ${error.message}`;
// 뮤테이션에 정보입력하여 사용하기
return (
<div>
<form
onSubmit={e => {
e.preventDefault();
addTodo({ variables: { text: input.value } });
input.value = '';
}}
>
<input
ref={node => {
input = node;
}}
/>
<button type="submit">Add Todo</button>
</form>
</div>
);
}
반응형
Apollo Client 란?
GraphQL와, 클라이언트를 연결해주는 Node.js 패키지
프론트엔드에서 다뤄지는 여러가지 데이터를 graphql을 사용해 DB에서 가져올 수 있도록 해준다.
Apollo Client 사용법
GraphQL & Apollo Client 설치
npm i graphql @apollo/client
javascript에서 GraphQL 가져오기
// React 프로젝트 내부 .js 파일
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
useQuery,
gql
} from "@apollo/client";
// ApolloClient 불러오기
// uri안에 GraphQL 서버 주소 넣기
// GraphQL 쿼리 결과를 저장하는데 사용할 cache 생성하기
const client = new ApolloClient({
uri: "https://localhost:4000",
cache: new InMemoryCache(),
});
React에서 GraphQL 쿼리 사용하기
client
.query({
query: gql`
query GetRates {
rates(currency: "USD") {
currency
}
}
`
})
.then(result => console.log(result));
React 프로젝트에 GraphQL 연결하기
// React 프로젝트 내부 .js 파일
import {
ApolloClient,
InMemoryCache,
ApolloProvider,
useQuery,
gql
} from "@apollo/client";
// ApolloClient 불러오기
const client = new ApolloClient({
uri: "https://localhost:4000",
cache: new InMemoryCache(),
});
function App() {
return (
<div>
<h2>My first Apollo app 🚀</h2>
</div>
);
}
// ApolloProvider로 GraphQL을 사용할 부분(React App 전체)를 감싸준다.
// apollo client를 통해 GraphQL을 연결해준다.
render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById('root'),
);
GraphQL 쿼리(Query) 사용하여, 데이터 가져오기
// 모듈 불러와 작업 준비
import { gql, useQuery } from "@apollo/client";
// GetExchangeRates 쿼리 사용하기 위해 쿼리문 작성해 저장하기
const EXCHANGE_RATES = gql`
query GetExchangeRates {
rates(currency: "USD") {
currency
rate
}
}
`;
// useQuery() 함수로, React 컴포넌트 내부에서 쿼리문 사용하기
function ExchangeRates() {
const { loading, error, data } = useQuery(EXCHANGE_RATES);
// 로딩시에 실행할 내용
if (loading) return <p>Loading...</p>;
// 에러시에 실행할 내용
if (error) return <p>Error :(</p>;
return data.rates.map(({ currency, rate }) => (
<div key={currency}>
<p>
{currency}: {rate}
</p>
</div>
));
}
GraphQL 뮤테이션(Mutation) 사용하여, 데이터 수정하기
// 모듈 불러와 작업 준비
import { gql, useMutation } from "@apollo/client";
// AddTodo 사용하기 위해 뮤테이션 작성해 저장하기
const ADD_TODO = gql`
mutation AddTodo($text: String!) {
addTodo(text: $text) {
id
text
}
}
`;
// useMutation() 함수로, React 컴포넌트 내부에서 뮤테이션 사용하기
function AddTodo() {
let input;
// 뮤테이션을 함수형식으로 불러온다. (addTodo)
const [addTodo, { data, loading, error }] = useMutation(ADD_TODO);
if (loading) return 'Submitting...';
if (error) return `Submission error! ${error.message}`;
// 뮤테이션에 정보입력하여 사용하기
return (
<div>
<form
onSubmit={e => {
e.preventDefault();
addTodo({ variables: { text: input.value } });
input.value = '';
}}
>
<input
ref={node => {
input = node;
}}
/>
<button type="submit">Add Todo</button>
</form>
</div>
);
}
반응형