๋ฐ๋ก ๊ฐ๊ธฐ : https://light9639.github.io/React-GraphQl-TypeScript/
โจ ๐ React TypeScript๋ฅผ GraphQl์ ์ด์ฉํ์ฌ ๋ง๋ ์์ ์ ๋๋ค. โจ
- React ์์ฑ
npm create-react-app my-app
# or
yarn create react-app my-app
- vite๋ฅผ ์ด์ฉํ์ฌ ํ๋ก์ ํธ๋ฅผ ์์ฑํ๋ ค๋ฉด
npm create vite@latest
# or
yarn create vite
- ํฐ๋ฏธ๋์์ ์คํ ํ ํ๋ก์ ํธ ์ด๋ฆ ๋ง๋ ํ React ์ ํ, Typescirpt-SWC ์ ํํ๋ฉด ์์ฑ ์๋ฃ.
- apollo-boost ๋ฐ react-apollo ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ค์นํ๊ธฐ
$ npm install apollo-boost react-apollo
# or
$ yarn add apollo-boost react-apollo
ApolloProvider
๋ฅผimport
ํ ํApp
ํ์ผ์ ๊ฐ์ผ๋ค.ApolloClient
๋ฅผ ๊ฐ์ ธ์จ ํuri
๋ถ๋ถ์ ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ฌGraphql
๋งํฌ๋ฅผ ์ ๋ ฅํ๋ค.
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
import ApolloClient, { InMemoryCache } from "apollo-boost";
import { ApolloProvider } from "react-apollo";
const client = new ApolloClient({
uri: "https://countries.trevorblades.com",
cache: new InMemoryCache()
});
ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(
<React.StrictMode>
<ApolloProvider client={client}>
<App />
</ApolloProvider>
</React.StrictMode>,
)
Continents
์ปดํฌ๋ํธ๋ฅผimport
ํ ํApp
์ปดํฌ๋ํธ ์์ ๋ฃ๋๋ค.
import { useState } from 'react'
import reactLogo from './assets/react.svg'
import './App.css'
import Continents from "./components/Continents";
export default function App(): JSX.Element {
return (
<div className="App">
<div>
<a href="https://graphql.org/" target="_blank">
<img src="https://camo.githubusercontent.com/07c382b68200c1a86d52d1682346e73e038b2f160c9afbc0af773fb3646882c8/68747470733a2f2f7777772e766563746f726c6f676f2e7a6f6e652f6c6f676f732f6772617068716c2f6772617068716c2d69636f6e2e737667" className="logo" alt="Vite logo" />
</a>
<a href="https://reactjs.org" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>GraphQl + React</h1>
<Continents></Continents>
</div>
)
}
gql
์์query
๋ฅผ ์ฌ์ฉํ์ฌ ๋ฐ์ดํฐ ์์ ์ฝ๋๋ช ๊ณผ ์ด๋ฆ์GET_CONTINENTS
๋ณ์๋ช ์ ํ ๋นํ๋ค.graphType
์ด๋ผ๋ ํ์ ์ ์ค์ ํ ๋ค ํ์ ์ ์ง์ ํด์ค๋ค.Query
์ปดํฌ๋ํธ ์์query={GET_CONTINENTS}
๋ฅผ ์ ๋ ฅํ๊ณ ๋ฐ์ ์ฝ๋๋ฅผ ์ ๋ ฅํ๋ค.- ๋ก๋ฉ์ค์ผ ๋๋
<p>Loading...</p>
, ์๋ฌ๊ฐ ๋ฌ์ ๋๋<p>Error!</p>
, ์ ์์ ์ผ ๊ฒฝ์ฐ์๋ ๋ฐ๋ณต๋ฌธ์ด ์คํ๋๋ค.
import React from "react";
import { ApolloError, gql } from "apollo-boost";
import { Query } from "react-apollo";
const GET_CONTINENTS = gql`
query {
continents {
code
name
}
}
`;
interface graphType {
loading?: boolean;
error?: ApolloError | undefined;
data: any;
}
interface mapType {
code: string;
name: string
}
export default function Continents(): JSX.Element {
return (
<React.Fragment>
<h2>Continents</h2>
<Query query={GET_CONTINENTS}>
{({ loading, error, data }: graphType) => {
if (loading) return <p>Loading...</p>;
if (error) return <p>Error!</p>;
return (
<React.Fragment>
{data.continents.map(({ code, name }: mapType) => (
<p key={code}>{name}</p>
))}
</React.Fragment>
);
}}
</Query>
</React.Fragment>
);
}