cache persist

김종민·2022년 5월 31일
0

insta-native

목록 보기
16/36

들억가기
휴대폰을 껏다 켯을 때, 혹시 server가 다운되어있거나, 꺼져있을떄,
마지막으로 접속해서 봤던 data들이 cache에 남아있게 해서,
서버가 다운되어도, 그 data들을 볼 수 있게 cache를 저장해 놓는것

npm i apollo3-cache-persist

1. App.js

import React, { useState } from 'react'
import { Ionicons } from '@expo/vector-icons'
import * as Font from 'expo-font'
import { Asset } from 'expo-asset'
import AppLoading from 'expo-app-loading'
import LoggedOutNav from './navigators/LoggedOutNav'
import { NavigationContainer } from '@react-navigation/native'
import LoggedInNav from './navigators/LoggedInNav'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { ApolloProvider, useReactiveVar } from '@apollo/client'
import { client, isLoggedInVar, TOKEN, tokenVar, cache } from './apollo' !!!!!!
import { AsyncStorageWrapper, persistCache } from 'apollo3-cache-persist' !!!!!!

export default function App() {
  const [loading, setLoading] = useState(true)
  const onFinish = () => setLoading(false)
  const isLoggedIn = useReactiveVar(isLoggedInVar)
  const preloadAssets = () => {
    const fontsToLoad = [Ionicons.font]
    const fontPromises = fontsToLoad.map((font) => Font.loadAsync(font))
    const imagesToLoad = [require('./assets/logo.png')]
    const imagesPromises = imagesToLoad.map((image) => Asset.loadAsync(image))
    return Promise.all([...fontPromises, ...imagesPromises])
  }
  const preload = async () => {
    const token = await AsyncStorage.getItem(TOKEN)
    if (token) {
      isLoggedInVar(true)
      tokenVar(token)
    }
    await persistCache({
      cache,
      storage: new AsyncStorageWrapper(AsyncStorage),
    })
    ///preload부분에서 persistCache, cache, storage를 설정한다.
    ///persistCache와 AsyncStorageWapper이 import되는 부분을 유의한다.
    ///cache를  import 할 수 있게 apollo.js에서 cache부분만 따로 분리해서,
    ///export 시킨다.
    
    return preloadAssets()
  }
  if (loading) {
    return (
      <AppLoading
        startAsync={preload}
        onError={console.warn}
        onFinish={onFinish}
      />
    )
  }

  return (
    <ApolloProvider client={client}>
      <NavigationContainer>
        {isLoggedIn ? <LoggedInNav /> : <LoggedOutNav />}
      </NavigationContainer>
    </ApolloProvider>
  )
}

2. apollo.js

import {
  makeVar,
  ApolloClient,
  InMemoryCache,
  createHttpLink,
} from '@apollo/client'
import { setContext } from '@apollo/client/link/context'
import { offsetLimitPagination } from '@apollo/client/utilities'
import AsyncStorage from '@react-native-async-storage/async-storage'

export const isLoggedInVar = makeVar(false)
export const tokenVar = makeVar('')
export const TOKEN = 'token'

export const logUserIn = async (token) => {
  await AsyncStorage.setItem(TOKEN, token)
  isLoggedInVar(true)
  tokenVar(token)
}
export const logUserOut = async () => {
  await AsyncStorage.removeItem(TOKEN)
  isLoggedInVar(false)
  tokenVar(null)
}

const httpLink = createHttpLink({
  uri: 'http://10.0.2.2:4000/graphql',
})

const authLink = setContext((_, { headers }) => {
  return {
    headers: {
      ...headers,
      token: tokenVar(),
    },
  }
})

********************************************************
export const cache = new InMemoryCache({
  typePolicies: {
    Query: {
      fields: {
        seeFeed: offsetLimitPagination(),
      },
    },
  },
})
원래, ApolloClient안에 들어 있던 cache부분을 App.js에서 import 할 수 있게
밖으로 cache부분은 꺼집어내어놓음,
***************************************************************

export const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache,
})
profile
코딩하는초딩쌤

0개의 댓글