Skip to content

Commit

Permalink
feat: migrate from asyncstorager to mmkv
Browse files Browse the repository at this point in the history
  • Loading branch information
Arnaud AMBROSELLI committed May 12, 2022
1 parent 46d3839 commit 9c1e52a
Show file tree
Hide file tree
Showing 28 changed files with 195 additions and 134 deletions.
25 changes: 23 additions & 2 deletions App.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,43 @@
import React from 'react';
import React, { useEffect, useState } from 'react';
import * as Sentry from '@sentry/react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { Provider } from 'react-redux';
import { RecoilRoot } from 'recoil';
import { PersistGate } from 'redux-persist/integration/react';
import { InteractionManager } from 'react-native';
import { persistor, store } from './src/redux/store';
import Router from './src/Router';
import './src/services/polyfills';

import { SENTRY_XXX } from './src/config';
import { ToastProvider } from './src/services/toast';
import './src/styles/theme';
import { RecoilRoot } from 'recoil';
import { hasMigratedFromAsyncStorage, migrateFromAsyncStorage } from './src/services/storage';

if (!__DEV__) {
Sentry.init({ dsn: SENTRY_XXX });
}

const App = () => {
// TODO: Remove `hasMigratedFromAsyncStorage` after a while (when everyone has migrated)
const [hasMigrated, setHasMigrated] = useState(hasMigratedFromAsyncStorage);

useEffect(() => {
if (!hasMigratedFromAsyncStorage) {
InteractionManager.runAfterInteractions(async () => {
try {
await migrateFromAsyncStorage();
setHasMigrated(true);
} catch (e) {
// TODO: fall back to AsyncStorage? Wipe storage clean and use MMKV? Crash app?
}
});
}
}, []);

console.log({ hasMigrated });
if (!hasMigrated) return null;

return (
<RecoilRoot>
<ToastProvider backgroundColor="#4030a5">
Expand Down
14 changes: 14 additions & 0 deletions ios/Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,9 @@ PODS:
- fmt (6.2.1)
- glog (0.3.5)
- libevent (2.1.12)
- MMKV (1.2.13):
- MMKVCore (~> 1.2.13)
- MMKVCore (1.2.13)
- OpenSSL-Universal (1.1.180)
- Permission-Camera (3.3.1):
- RNPermissions
Expand Down Expand Up @@ -287,6 +290,9 @@ PODS:
- react-native-config/App (= 1.4.5)
- react-native-config/App (1.4.5):
- React-Core
- react-native-mmkv (2.4.1):
- MMKV (>= 1.2.13)
- React-Core
- react-native-netinfo (5.9.10):
- React-Core
- react-native-safe-area-context (3.4.1):
Expand Down Expand Up @@ -463,6 +469,7 @@ DEPENDENCIES:
- React-jsinspector (from `../node_modules/react-native/ReactCommon/jsinspector`)
- react-native-camera (from `../node_modules/react-native-camera`)
- react-native-config (from `../node_modules/react-native-config`)
- react-native-mmkv (from `../node_modules/react-native-mmkv`)
- "react-native-netinfo (from `../node_modules/@react-native-community/netinfo`)"
- react-native-safe-area-context (from `../node_modules/react-native-safe-area-context`)
- react-native-webview (from `../node_modules/react-native-webview`)
Expand Down Expand Up @@ -508,6 +515,8 @@ SPEC REPOS:
- FlipperKit
- fmt
- libevent
- MMKV
- MMKVCore
- OpenSSL-Universal
- Sentry
- YogaKit
Expand Down Expand Up @@ -553,6 +562,8 @@ EXTERNAL SOURCES:
:path: "../node_modules/react-native-camera"
react-native-config:
:path: "../node_modules/react-native-config"
react-native-mmkv:
:path: "../node_modules/react-native-mmkv"
react-native-netinfo:
:path: "../node_modules/@react-native-community/netinfo"
react-native-safe-area-context:
Expand Down Expand Up @@ -630,6 +641,8 @@ SPEC CHECKSUMS:
fmt: ff9d55029c625d3757ed641535fd4a75fedc7ce9
glog: 5337263514dd6f09803962437687240c5dc39aa4
libevent: 4049cae6c81cdb3654a443be001fb9bdceff7913
MMKV: aac95d817a100479445633f2b3ed8961b4ac5043
MMKVCore: 3388952ded307e41b3ed8a05892736a236ed1b8e
OpenSSL-Universal: 1aa4f6a6ee7256b83db99ec1ccdaa80d10f9af9b
Permission-Camera: bae27a8503530770c35aadfecbb97ec71823382a
Permission-Notifications: 4b21cfdd5e8aab2cbb1f117aaa17b44e1f5736c4
Expand All @@ -647,6 +660,7 @@ SPEC CHECKSUMS:
React-jsinspector: 41e58e5b8e3e0bf061fdf725b03f2144014a8fb0
react-native-camera: b8cc03e2feec0c04403d0998e37cf519d8fd4c6f
react-native-config: 6502b1879f97ed5ac570a029961fc35ea606cd14
react-native-mmkv: b5c7f9bc369eef2b8a2aa36e8a15949989fa823f
react-native-netinfo: 30fb89fa913c342be82a887b56e96be6d71201dd
react-native-safe-area-context: 9e40fb181dac02619414ba1294d6c2a807056ab9
react-native-webview: 0aa2cde4ee7e3e1c5fffdf64dbce9c709aa18155
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
"react-native-config": "^1.4.3",
"react-native-device-info": "^5.5.3",
"react-native-gesture-handler": "^1.10.3",
"react-native-mmkv": "^2.4.1",
"react-native-permissions": "^3.0.5",
"react-native-push-notification": "^7.4.0",
"react-native-reanimated": "2.3.0-alpha.2",
Expand Down Expand Up @@ -81,7 +82,6 @@
"jest": {
"preset": "react-native",
"setupFiles": [
"./__mocks__/AsyncStorage.js",
"./__mocks__/Sentry.js"
],
"forceCoverageMatch": [
Expand Down
5 changes: 2 additions & 3 deletions src/Router.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React, { Component } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
Expand All @@ -22,6 +21,7 @@ import WelcomeScreen from './scenes/WelcomeScreen/WelcomeScreen';
import AppStateHandler from './services/AppStateHandler';
import matomo from './services/matomo';
import NotificationService from './services/notifications';
import { storage } from './services/storage';

const Tabs = createBottomTabNavigator();
const TabsNavigator = ({ navigation }) => {
Expand Down Expand Up @@ -111,8 +111,7 @@ class Router extends Component {
initView = async () => {
await matomo.initMatomo();
await matomo.logAppVisit('initApp');
// await AsyncStorage.clear();
const onBoardingDone = await AsyncStorage.getItem('@OnboardingDoneWithCGU');
const onBoardingDone = storage.getBoolean('@OnboardingDoneWithCGU');
if (!onBoardingDone) return this.setState({ initialRouteName: 'WELCOME' });
return this.setState({ initialRouteName: 'TABS' });
};
Expand Down
6 changes: 3 additions & 3 deletions src/components/Quizz/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import React, { useEffect, useState } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { createStackNavigator } from '@react-navigation/stack';
import styled from 'styled-components';
import Background from '../Background';
import ProgressBar from '../ProgressBar';
import UnderlinedButton from '../UnderlinedButton';
import Question from './Question';
import { fetchStoredAnswers } from './utils';
import { storage } from '../../services/storage';

/*
HOW DOES THE QUESTIONS WORK:
Expand Down Expand Up @@ -44,14 +44,14 @@ const Quizz = ({ memoryKeyAnswers, memoryKeyResult, questions, route, mapAnswers
const endOfQuestions = questionIndex === questions.length - 1;

// await matomo.logQuizzAnswer({ questionKey, answerKey, score });
await AsyncStorage.setItem(memoryKeyAnswers, JSON.stringify(newAnswers));
storage.set(memoryKeyAnswers, JSON.stringify(newAnswers));

if (endOfQuestions) {
const addictionResult = mapAnswersToResult(questions, newAnswers);
// await matomo.logAddictionResult(addictionResult);
// await matomo.logQuizzFinish();
if (addictionResult) {
await AsyncStorage.setItem(memoryKeyResult, JSON.stringify(addictionResult));
storage.set(memoryKeyResult, JSON.stringify(addictionResult));
}
setState({ resultKey: addictionResult });
}
Expand Down
10 changes: 5 additions & 5 deletions src/components/Quizz/utils.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
import { capture } from '../../services/sentry';
import { storage } from '../../services/storage';

// Utils
export const findQuestion = (questions, questionKey) =>
Expand All @@ -9,8 +9,8 @@ export const getAnswerScore = (questions, answers, questionKey) =>
findAnswer(findQuestion(questions, questionKey), answers[questionKey])?.score;

export const getGenderFromLocalStorage = async () => {
const storedAnswers = await AsyncStorage.getItem('@Quizz_answers');
if (storedAnswers !== null) {
const storedAnswers = storage.getString('@Quizz_answers');
if (typeof storedAnswers === 'string') {
const newAnswers = JSON.parse(storedAnswers);
return newAnswers.gender;
}
Expand All @@ -28,14 +28,14 @@ export const fetchStoredAnswers = async ({ memoryKeyAnswers, memoryKeyResult, qu

const toReturn = { answers: null, result: null };
try {
const storedAnswers = await AsyncStorage.getItem(memoryKeyAnswers);
const storedAnswers = storage.getString(memoryKeyAnswers);
if (storedAnswers !== null) {
toReturn.answers = JSON.parse(storedAnswers);
} else {
toReturn.answers = computeInitAnswersState();
}
if (memoryKeyResult) {
const storedResultKey = await AsyncStorage.getItem(memoryKeyResult);
const storedResultKey = storage.getBoolean(memoryKeyResult);
if (storedResultKey !== null) {
toReturn.result = JSON.parse(storedResultKey);
}
Expand Down
37 changes: 0 additions & 37 deletions src/hooks/useStateWithAsyncStorage.js

This file was deleted.

6 changes: 3 additions & 3 deletions src/redux/persistConfig.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
import { createMigrate } from 'redux-persist';
import { reduxStorage } from '../services/storage';

const migrations = {};

export default {
key: 'addicto',
key: 'addicto2',
version: 4,
storage: AsyncStorage,
storage: reduxStorage,
debug: false,
migrate: createMigrate(migrations, { debug: false }),
blacklist: [
Expand Down
6 changes: 3 additions & 3 deletions src/scenes/AddDrink/BarCodeReader.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React, { Component } from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { Alert, TouchableWithoutFeedback } from 'react-native';
import { RNCamera } from 'react-native-camera';
import styled from 'styled-components';
Expand All @@ -15,6 +14,7 @@ import {
CameraButton,
CameraButtonsContainerSafe,
} from './styles';
import { storage } from '../../services/storage';

class BarCodeReader extends Component {
state = {
Expand All @@ -30,7 +30,7 @@ class BarCodeReader extends Component {
};

showScanAlert = async () => {
const dontShowScanAlert = await AsyncStorage.getItem('@ScanAlert');
const dontShowScanAlert = storage.getString('@ScanAlert');
if (dontShowScanAlert) return;
setTimeout(() => {
if (this.props.visible) {
Expand All @@ -45,7 +45,7 @@ class BarCodeReader extends Component {
{
text: 'Ne plus afficher',
onPress: async () => {
await AsyncStorage.setItem('@ScanAlert', 'true');
storage.set('@ScanAlert', 'true');
},
style: 'cancel',
},
Expand Down
22 changes: 11 additions & 11 deletions src/scenes/ConsoFollowUp/Diagram.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import UnderlinedButton from '../../components/UnderlinedButton';
import { dateIsBeforeOrToday } from '../../helpers/dateHelpers';
import { fakeConsoData } from '../../reference/mocks/fakeConsoData';
import { storage } from '../../services/storage';
import { screenHeight } from '../../styles/theme';
import {
checkIfThereIsDrinks,
Expand Down Expand Up @@ -72,12 +72,12 @@ const Diagram = ({
useEffect(() => {
(async () => {
try {
const storedValue = await AsyncStorage.getItem('@Quizz_answers');
const storedValue = storage.getString('@Quizz_answers');
if (!storedValue) return;
const quizzAnswers = JSON.parse(storedValue);
if (!quizzAnswers) return;
setHighestAcceptableDosesPerDay(getAcceptableDosePerDay(quizzAnswers.gender));
} catch (e) { }
} catch (e) {}
})();
}, []);

Expand Down Expand Up @@ -177,16 +177,16 @@ Diagram.defaultProps = {

const makeStateToProps =
() =>
(realState, { asPreview }) => {
const state = asPreview ? { conso: fakeConsoData.partial } : realState;
(realState, { asPreview }) => {
const state = asPreview ? { conso: fakeConsoData.partial } : realState;

return {
days: getDaysForDiagram(state),
thereIsDrinks: checkIfThereIsDrinks(state),
dailyDoses: getDailyDoses(state),
highestDailyDose: getHighestDailyDoses(state),
};
return {
days: getDaysForDiagram(state),
thereIsDrinks: checkIfThereIsDrinks(state),
dailyDoses: getDailyDoses(state),
highestDailyDose: getHighestDailyDoses(state),
};
};

const mergeProps = (stateProps, dispatch, ownProps) => ({
...ownProps,
Expand Down
10 changes: 5 additions & 5 deletions src/scenes/Defis/Defi7Days/Defi7Days.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useFocusEffect } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import React, { useEffect, useState } from 'react';
import Background from '../../../components/Background';
import HeaderBackground from '../../../components/HeaderBackground';
import { storage } from '../../../services/storage';
import Reminder from '../../Infos/Reminder';
import QuizzEvaluateConso from '../../Quizzs/QuizzEvaluateConso';
import QuizzLifeQuality from '../../Quizzs/QuizzLifeQuality';
Expand All @@ -23,7 +23,7 @@ const Defi7DaysStack = createStackNavigator();
const Defi7DaysNavigator = () => {
const [initialScreen, setInitialScreen] = useState(null);
const initNavigator = async () => {
const defiStartedAt = await AsyncStorage.getItem('DEFI_7_JOURS_STARTED_AT');
const defiStartedAt = storage.getString('DEFI_7_JOURS_STARTED_AT');
if (defiStartedAt) return setInitialScreen('DEFI_7_DAYS_MENU');
return setInitialScreen('ONBOARDING');
};
Expand Down Expand Up @@ -108,9 +108,9 @@ const Defi7DaysMenu = ({ navigation }) => {
const [lastUpdate, setLastUpdate] = useState('');

const getValidatedDays = async () => {
const storedLastUpdate = await AsyncStorage.getItem('DEFI_7_JOURS_LAST_UPDATE');
const storedLastUpdate = storage.getString('DEFI_7_JOURS_LAST_UPDATE');
if (storedLastUpdate) setLastUpdate(storedLastUpdate);
const storedValidateDays = await AsyncStorage.getItem('DEFI_7_JOURS_VALIDATED_DAYS');
const storedValidateDays = storage.getString('DEFI_7_JOURS_VALIDATED_DAYS');
if (storedValidateDays) setValidateDays(Number(storedValidateDays));
};

Expand All @@ -125,7 +125,7 @@ const Defi7DaysMenu = ({ navigation }) => {

const hackAndUnlockDay = async (day) => {
await new Promise((res) => setTimeout(res, 1000)); // better UX
await AsyncStorage.setItem('DEFI_7_JOURS_VALIDATED_DAYS', `${day}`);
storage.set('DEFI_7_JOURS_VALIDATED_DAYS', `${day}`);
setLastUpdate('UNLOCK');
setValidateDays(day);
};
Expand Down
Loading

0 comments on commit 9c1e52a

Please sign in to comment.