설치
npm install @apollo/client graphql
import { InMemoryCache, ApolloClient } from "@apollo/client";
const client = new ApolloClient({
uri: "http://localhost:4000",
cache: new InMemoryCache(),
});
export default client;
import React from "react";
import ReactDOM from "react-dom";
import App from "./components/App";
import { ApolloProvider } from "@apollo/client";
import client from "./apollo";
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById("root")
);
data받아오기
import { gql, useQuery } from "@apollo/client";
const GET_MOVIES = gql`
{
movies {
id
medium_cover_image
}
}
`;
const Home = () => {
const { loading, error, data } = useQuery(GET_MOVIES);
console.log(data);
return (
<Container>
<Header>
<Title>Apollo 2020</Title>
<Subtitle>I love GraphQL</Subtitle>
</Header>
{loading && <Loading>Loading...</Loading>}
{!loading &&
data.movies &&
data.movies.map(m => <Movie key={m.id} id={m.id} />)}
</Container>
);
};
Movie Detail
const GET_MOVIE = gql`
query getMovie($id: Int!) {
movie(id: $id) {
id
title
medium_cover_image
description_intro
}
}
`;
const Detail = () => {
const { id } = useParams();
const { loading, error, data } = useQuery(GET_MOVIE, {
variables: { id: +id },
});
console.log(data);
return (
<div>
{loading && <Loading>Loading...</Loading>}
{!loading && data && <h1>{data.movie.title}</h1>}
</div>
);
};
client에서 query넣기
const client = new ApolloClient({
uri: "http://localhost:4000",
cache: new InMemoryCache(),
resolvers: {
Movie: { //Query에 있는 값이어야한다
isLiked: () => false, //client에서 설정해준 Query에는 없다
},
},
});
@client
- client에서 설정해 준 값이니깐 @client를 적어줘야한다.
const GET_MOVIES = gql`
{
movies {
id
medium_cover_image
isLiked @client
}
}
`;