<React Typescript Setup Tutorial> 1. Apollo 세팅하기 (작성 중..)

기본 개발 환경 구축

create-react-app sample-client --typescript
yarn add apollo-boost graphql react-apollo
// apollo.ts

import ApolloClient, { Operation } from 'apollo-boost'

const client = new ApolloClient({
  uri: 'http://localhost:4000/graphql',
})

export default client
// index.tsx

import React from 'react'
import { ApolloProvider } from 'react-apollo'
import ReactDOM from 'react-dom'
import client from './apollo'

import App from './App'

ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById('root')
)
import ApolloClient, { Operation } from 'apollo-boost'

const client = new ApolloClient({
  clientState: {
    defaults: {
      auth: {
        __typename: 'Auth',
        isLoggedIn: Boolean(localStorage.getItem('authToken')),
      },
    },
    resolvers: {
      Mutation: {
        logUserIn: (_, { token }, { cache }) => {
          localStorage.setItem('authToken', token)
          cache.writeData({
            data: {
              auth: {
                __typename: 'Auth',
                isLoggedIn: true,
              },
            },
          })
          return null
        },
        logUserOut: (_, __, { cache }) => {
          localStorage.removeItem('authToken')
          cache.writeData({
            data: {
              auth: {
                __typename: 'Auth',
                isLoggedIn: false,
              },
            },
          })
          return null
        },
      },
    },
  },
  request: async (operation: Operation) => {
    operation.setContext({
      headers: {
        'X-User-Token': localStorage.getItem('authToken') || '',
      },
    })
  },
  uri: 'http://localhost:4000/graphql',
})

export default client

Reference


Jaewoo Cho (flowkater)
Written by@Jaewoo Cho (flowkater)
작은 스타트업 합니다. 항상 생존이 우선이지만 그래도 하고 싶은거 하는 기획자 겸 개발자입니다. 아참, 데이터 과학 강의도 합니다.

GitHubFacebook