Development/GraphQL

[GraphQL / Apollo] 도입해보기

안다희 2020. 3. 2. 00:44
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 써서.

 

4. 

출처: https://mingos-habitat.tistory.com/34 [밍고의서식지:티스토리]