728x90
    
    
  https://coding-dahee.tistory.com/111
아폴로 습득 후 직접 해보기!
목적: redux, context 대체.
1. isLoggedIn 이라는 변수 만들고 cache에서 가져와보기
client/src/apollo/Apollo.js
import {resolvers, typeDefs} from './resolvers';
import {ApolloClient} from 'apollo-client';
import {HttpLink} from 'apollo-link-http';
import {InMemoryCache} from 'apollo-cache-inmemory';
const cache = new InMemoryCache();
const link = new HttpLink({
  uri: 'http://localhost:4000/',
});
cache.writeData({
  data: {
    isLoggedIn: true,
  },
});
const client = new ApolloClient({
  cache,
  link,
  typeDefs, // 로컬상태
  resolvers, // 로컬상태
});
export default client;
ApolloClient 만들어주고 cache.writeData 할 때 초기화 시켜주기
client/src/apollo/queries.js
import gql from 'graphql-tag';
export const GET_STICKS = gql`
  {
    sticks {
      from
      to
    }
  }
`;
export const GET_LOCAL_DATA = gql`
  query getLocalData {
    isLoggedIn @client
  }
`;
@client 붙여주기!
client/src/apollo/resolvers.js
import {GET_LOCAL_DATA} from './queries';
export const typeDefs = `
    extend schema {
        query: Query
        mutation: Mutation
    }
    
`;
export const resolvers = {
  Query: {
    isLoggedIn: (_, __, {cache}) => {
      const queryResult = cache.readQuery({
        query: GET_LOCAL_DATA,
      });
      console.log('queryResult', queryResult);
      if (queryResult) {
        return queryResult;
      }
    },
  },
};
cache.readQuery로 가져온다.
2. isLoggedIn 값 변경해보기
import {GET_LOCAL_DATA, GET_MOVIES} from '../apollo/queries';
import {Text, TouchableOpacity, View} from 'react-native';
import BasicText from '../components/BasicText';
import {BasicView} from '../components/BasicView';
import React from 'react';
import {useApolloClient} from '@apollo/react-hooks';
import {useQuery} from '@apollo/react-hooks';
const Sub = () => {
  const {loading: l1, data: d1} = useQuery(GET_MOVIES);
  const {loading: l2, data: d2} = useQuery(GET_LOCAL_DATA);
  const client = useApolloClient();
  console.log(l1, d1);
  console.log(l2, d2);
  return (
    <TouchableOpacity
      onPress={() => {
        // toggle isLoggedIn
        client.writeData({data: {isLoggedIn: !d2.isLoggedIn}});
        // client.writeData({data: {isLoggedIn: !d2.isLoggedIn}});
        // writeData 말고 mutation 이용하는거 해보기
      }}>
      <BasicText />
    </TouchableOpacity>
  );
};
export default Sub;
3. API에서 가져온 데이터 movies를 로컬데이터로 바꾸고, mutation 써서 요리조기 바꿔보기.
'Study > GraphQL' 카테고리의 다른 글
| GQL서버 init (0) | 2020.04.10 | 
|---|---|
| [GraphQL] passport로 인증기능 만들기 (2) | 2020.03.23 | 
| [GraphQL] apollo-server와 express 연결하기 (0) | 2020.03.22 | 
| [GraphQL / Apollo] 오프라인 노트앱 만들기 (0) | 2020.02.16 | 
| Facebook도 쓰는 GraphQL 정복하기 (0) | 2019.12.04 |