GithubHelp home page GithubHelp logo

Comments (13)

booboothefool avatar booboothefool commented on May 5, 2024 2

Just ran into this issue and @hariroshan's solution worked great. Much appreciated.

Here is my package.json for science:

    "apollo-boost": "^0.1.7",
    "apollo-cache-persist": "^0.1.1",
    "apollo-link-context": "^1.0.9",
    "apollo-link-http": "^1.5.4",
    "apollo-link-schema": "^1.1.0",
    "apollo-link-state": "^0.4.1",
    "apollo-link-ws": "^1.0.9",
    "graphql": "^0.13.2",
    "graphql-iso-date": "^3.5.0",
    "graphql-tag": "^2.9.2",
    "graphql-tools": "^3.0.2",
    "react": "16.3.1",
    "react-apollo": "^2.1.4",
    "react-dom": "16.0.0",
    "react-native": "https://github.com/expo/react-native/archive/sdk-30.0.0.tar.gz",
    "subscriptions-transport-ws": "^0.9.15",

from apollo-cache-persist.

jamesreggio avatar jamesreggio commented on May 5, 2024 1

Oh, that's super odd that the caches are different! I'll dig in and see if I can figure out what's up.

from apollo-cache-persist.

Lucas-Geitner avatar Lucas-Geitner commented on May 5, 2024 1

Same for web ! thank you so much 💯

from apollo-cache-persist.

vpfaulkner avatar vpfaulkner commented on May 5, 2024 1

I also was experiencing this and the above fix works

from apollo-cache-persist.

hariroshan avatar hariroshan commented on May 5, 2024 1

App.js

import React from 'react';
import { Platform, StatusBar, StyleSheet, View, AsyncStorage } from 'react-native';
import { AppLoading, Asset, Font } from 'expo';
import { Ionicons } from '@expo/vector-icons';
import RootNavigation from './navigation/RootNavigation';
import ApolloClient from 'apollo-boost'
import { ApolloProvider } from 'react-apollo'
import { InMemoryCache } from 'apollo-cache-inmemory';
import { CachePersistor } from 'apollo-cache-persist';

// AsyncStorage.clear()
// AsyncStorage.getAllKeys().then(console.log)
// AsyncStorage.getItem('apollo-cache-persist').then((tem) => {
//   // console.log(tem)
//   // cache.restore(tem)
// })


const SCHEMA_VERSION = '1'; // Must be a string.
const SCHEMA_VERSION_KEY = 'JOKED-SCHEMA';
const defaultOptions = {
  watchQuery: {
    fetchPolicy: 'cache-and-network',
    errorPolicy: 'ignore',
  },
  query: {
    fetchPolicy: 'cache-and-network',
    errorPolicy: 'all',
  },
  mutate: {
    errorPolicy: 'all'
  }
}
const cache = new InMemoryCache()
const client = new ApolloClient({
  uri: "http://192.168.0.106:4000",
  cache,
  defaultOptions
})

const persistor = new CachePersistor({
  cache: client.cache,
  storage: AsyncStorage,
  trigger: 'background',
  debug: true,
});
console.log('Caches are equal', cache === client.cache)

client.persistor = persistor
// persistor.restore()

export default class App extends React.Component {
  state = {
    isLoadingComplete: false,
  };

  render() {
    if (!this.state.isLoadingComplete && !this.props.skipLoadingScreen) {
      return (
        <AppLoading
          startAsync={this._loadResourcesAsync}
          onError={this._handleLoadingError}
          onFinish={this._handleFinishLoading}
        />
      );
    } else {
      return (
        <ApolloProvider client={client} >
          <View style={styles.container}>
            {Platform.OS === 'ios' && <StatusBar barStyle="default" />}
            <RootNavigation />
          </View>
        </ApolloProvider>
      );
    }
  }

  _loadResourcesAsync = async () => {
    await this._rehydrateCache()
    return Promise.all([
      Asset.loadAsync([
        require('./assets/images/robot-dev.png'),
        require('./assets/images/robot-prod.png'),
      ]),
      Font.loadAsync({
        // This is the font that we are using for our tab bar
        ...Ionicons.font,
        // We include SpaceMono because we use it in HomeScreen.js. Feel free
        // to remove this if you are not using it in your app
        'space-mono': require('./assets/fonts/SpaceMono-Regular.ttf'),
        'san-francisco': require('./assets/fonts/SanFrancisco.ttf'),
      }),
    ])
  }

  _rehydrateCache = async () => {

    // Read the current schema version from AsyncStorage.
    const currentVersion = await AsyncStorage.getItem(SCHEMA_VERSION_KEY);

    if (currentVersion === SCHEMA_VERSION) {
      // If the current version matches the latest version,
      // we're good to go and can restore the cache.
      // console.log(cache)
      await persistor.restore();
      // await persistor.getLogs(console.log)
      // console.log(await AsyncStorage.getItem('apollo-cache-persist'))

    } else {
      // Otherwise, we'll want to purge the outdated persisted cache
      // and mark ourselves as having updated to the latest version.
      await persistor.purge();
      await AsyncStorage.setItem(SCHEMA_VERSION_KEY, SCHEMA_VERSION);
    }
  }

  _handleLoadingError = error => {
    // In this case, you might want to report the error to your error
    // reporting service, for example Sentry
    console.warn(error);
  };

  _handleFinishLoading = () => {
    this.setState({ isLoadingComplete: true });
  };
}


const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
});

from apollo-cache-persist.

jamesreggio avatar jamesreggio commented on May 5, 2024

This is very odd.

I'd like to dig in and see if there's something we're doing wrong in this package. Can you do answer two questions for me?

  1. Can you copy-paste the line that has import { ApolloClient } from '...' from your app? There are a couple of different packages that expose ApolloClient. Also, could you tell me which version of whatever package it is that you're using for ApolloClient?

  2. Can you add this log-line after persistCache and tell me what it reports?
    console.log('Caches are equal', cache === client.cache);

Thanks in advance.

from apollo-cache-persist.

hariroshan avatar hariroshan commented on May 5, 2024

Thanks for your kind reply.
Answer to your questions,

  1. Here is my import line import ApolloClient from 'apollo-boost' // version "apollo-boost": "^0.1.7"
  2. Caches are equal false

Here is my init code.

const cache = new InMemoryCache()
const client = new ApolloClient({
  uri: "http://192.168.0.106:4000",
  cache,
  defaultOptions
})

const persistor = new CachePersistor({
  cache: client.cache,
  storage: AsyncStorage,
  trigger: 'background',
  debug: true,
});
console.log('Caches are equal', cache === client.cache)

from apollo-cache-persist.

jamesreggio avatar jamesreggio commented on May 5, 2024

I've tried to reproduce this, but I cannot seem to get into the position where there are two caches.

Can somebody please share their entire package.json, as well as the entirety of the file that initializes their ApolloClient and cache persistence?

from apollo-cache-persist.

hariroshan avatar hariroshan commented on May 5, 2024

package.json

  "main": "node_modules/expo/AppEntry.js",
  "private": true,
  "scripts": {
    "test": "node ./node_modules/jest/bin/jest.js --watchAll",
    "start": "react-native-scripts start",
    "eject": "react-native-scripts eject",
    "android": "react-native-scripts android",
    "ios": "react-native-scripts ios"
  },
  "jest": {
    "preset": "jest-expo"
  },
  "dependencies": {
    "@expo/samples": "2.1.1",
    "apollo-boost": "^0.1.7",
    "apollo-cache-persist": "^0.1.1",
    "expo": "^27.0.1",
    "formik": "^0.11.11",
    "graphql": "^0.13.2",
    "graphql-tag": "^2.9.2",
    "react": "16.3.1",
    "react-apollo": "^2.1.4",
    "react-native": "~0.55.2",
    "react-navigation": "2.0.0",
    "yup": "^0.25.1"
  },
  "devDependencies": {
    "jest-expo": "^27.0.0"
  }
}

from apollo-cache-persist.

wtrocki avatar wtrocki commented on May 5, 2024

I have seen this issue with Apollo boost duplicating cache. However recent version 0.3.0 should work fine. If we still see the issues please shout. Problem will happen stricty when using boost.

from apollo-cache-persist.

khaphannm avatar khaphannm commented on May 5, 2024

@hariroshan With this persistor in your App.js, how can u use it outside of App.js ?

from apollo-cache-persist.

AnderLuiz avatar AnderLuiz commented on May 5, 2024

I have a problem like that when I update the cache after a mutation with react-native and apollo-3, but happens with apollo-2 as well. It seems there are multiple cache instances.
If I call persistor.persist() inside the update function manually, the correct cache is persisted, but once I go to background, the another cache instance is persisted.

const mutationOptions = {
   mutation: DELETE_CITY,
   variables: {
     id: item.id,
   },
   update: (store, { data }) => {
     const cities = this.props.client.readQuery(this.state.queryData).allCities;
     const allCities = cities.filter(city => city.id !== item.id);
     store.writeQuery({ ...this.state.queryData, data: { allCities } });
     persistor.persist();  // If i persist here, the correct cache is persisted 
   },
   optimisticResponse: {
     data: {
       deleteCity: {
         id: item.id,
         __typename: 'City',
       },
     },
   },
 };

image
The first log, is when I persist inside the update function, and the second log is when the app goes to background and cache is persisted.

I tried @hariroshan solution but did not work.

EDIT: Figured out apollo-cache-persist can't persist optimisticResponses;

from apollo-cache-persist.

jspizziri avatar jspizziri commented on May 5, 2024

Closing this due to inactivity. Please let me know if it needs to be opened back up.

from apollo-cache-persist.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.