Skip to content
This repository has been archived by the owner on Apr 2, 2024. It is now read-only.

Context Memoization #388

Merged
merged 4 commits into from
Dec 16, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
}
],
"react/no-array-index-key": 0,
"react/jsx-no-constructed-context-values": 2,
"react/jsx-one-expression-per-line": 0,
"react/jsx-indent": [
2,
Expand All @@ -99,7 +100,7 @@
"react-native/no-color-literals": 0,
"react-native/no-raw-text": 0,
"react-native/no-single-element-style-arrays": 2,
"react-hooks/exhaustive-deps": 0,
"react-hooks/exhaustive-deps": 1,
"react/jsx-filename-extension": "off",
"jsx-quotes": [
"error",
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

Intaller dépendances : `npm i`

Installer husky : `npx husky install`

IOS :
- `sudo xcode-select --switch /Applications/Xcode.app`
- `cd ios && pos install`
Expand Down
3 changes: 1 addition & 2 deletions src/components/map/DropyMapMarker.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import Styles, { Colors, Fonts } from '../../styles/Styles';
import DropyPopup from '../../assets/svgs/dropyPopup.svg';
import { createDropTimeString } from '../../utils/time';


const DropyMapMarker = ({ dropy, onPress }) => {
const [dropTimeString, setDropTimeString] = useState('0s');

Expand All @@ -28,7 +27,7 @@ const DropyMapMarker = ({ dropy, onPress }) => {
const interval = setInterval(updateTimeString, intervalDuration);

return () => clearInterval(interval);
}, [dropy?.isUserDropy]);
}, [dropy]);

if (!dropy.reachable && !dropy?.isUserDropy)
return <RadarMarker dropy={dropy} />;
Expand Down
2 changes: 1 addition & 1 deletion src/screens/DisplayDropyMediaScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const DisplayDropyMediaScreen = ({ navigation, route }) => {
const confirmGoBack = async () => {
const result = await sendAlert({
title: 'Ne pas répondre ?',
description: 'Tu ne pourras plus voir ce drop ni commencer à discuter avec l\'utilisateur qui l'a créé',
description: 'Tu ne pourras plus voir ce drop ni commencer à discuter avec l\'utilisateur qui l\'a créé',
validateText: 'Ne pas répondre',
denyText: 'Non, je veux répondre',
});
Expand Down
10 changes: 5 additions & 5 deletions src/screens/Onboarding.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
} from 'react-native';
import React, { useContext, useEffect, useRef, useState } from 'react';
import { responsiveHeight, responsiveWidth } from 'react-native-responsive-dimensions';
import { AntDesign, MaterialCommunityIcons, MaterialIcons } from '@expo/vector-icons';
import { AntDesign, Ionicons, MaterialCommunityIcons } from '@expo/vector-icons';
import { openCamera, openPicker } from 'react-native-image-crop-picker';
import { useActionSheet } from '@expo/react-native-action-sheet';
import { PERMISSIONS, request, requestNotifications, RESULTS } from 'react-native-permissions';
Expand Down Expand Up @@ -426,7 +426,7 @@ export default function Onboarding({ navigation }) {
<Text style={{ fontSize: 40 }}>👋</Text>
<View style={{ ...Styles.center }}>
<Text style={{ ...styles.title, fontSize: 35 }}>Salut !</Text>
<Text style={{ ...styles.subtitle, fontSize: 20 }}>Lance toi dans l\'aventure Dropy</Text>
<Text style={{ ...styles.subtitle, fontSize: 20 }}>{'Lance toi dans l\'aventure Dropy'}</Text>
</View>
<LoadingGlassButton
onPress={() => viewSliderRef.current?.goToView(2)}
Expand Down Expand Up @@ -519,7 +519,7 @@ export default function Onboarding({ navigation }) {
<Text style={styles.title}>Active la géolocalisation</Text>
<Text style={styles.subtitle}>{'Sinon tu ne pourras pas utiliser l\'app'}</Text>
</View>
<MaterialIcons name='location-pin' size={60} color={Colors.grey} />
<Ionicons name='location-outline' size={60} color={Colors.grey} />
<LoadingGlassButton
loading={loading}
onPress={() => requestGeolocationPermissions(() => viewSliderRef.current?.goToView(6))}
Expand All @@ -532,7 +532,7 @@ export default function Onboarding({ navigation }) {
<Text style={styles.title}>{'Ne rate aucun message'}</Text>
<Text style={styles.subtitle}>Active les notifications</Text>
</View>
<MaterialCommunityIcons name='bell-ring' size={50} color={Colors.grey} />
<Ionicons name='md-chatbubbles-outline' size={50} color={Colors.grey} />
<LoadingGlassButton
loading={loading}
onPress={() => requestNotificationsPermissions(
Expand All @@ -547,7 +547,7 @@ export default function Onboarding({ navigation }) {
<View style={{ marginBottom: 30, ...Styles.center }}>
<Text style={styles.title}>{'Reste à l\'affût !'}</Text>
<Text style={styles.subtitle}>
{'Active le mode radar pour ne manquer aucun drop, même quand l\'application n'est pas lancée !'}
{'Active le mode radar pour ne manquer aucun drop, même quand l\'application n\'est pas lancée !'}
</Text>
<Text style={{ ...styles.subtitle, ...Fonts.regular(10.5, Colors.grey), marginVertical: 3 }}>
{'Ce mode utilise la géolocalisation en arrière plan.'}
Expand Down
112 changes: 57 additions & 55 deletions src/states/BackgroundGolocationContextProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,14 @@
// https://github.com/transistorsoft/react-native-background-geolocation/wiki/Philosophy-of-Operation
//

import React, { createContext, useContext, useEffect, useState } from 'react';
import React, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useState
} from 'react';
import { StyleSheet, Text, TouchableOpacity, View } from 'react-native';

import BackgroundGeolocation from 'react-native-background-geolocation';
Expand All @@ -16,6 +23,35 @@ import { UserContext } from './UserContextProvider';

export const BackgroundGeolocationContext = createContext(null);

const setupBackgroundGeolocation = async (authTokens) => {
const { accessToken, refreshToken, expires } = authTokens;

const backgroundGeolocationReady = await BackgroundGeolocation.ready({
desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_NAVIGATION,
useSignificantChangesOnly: true,

logLevel: BackgroundGeolocation.LOG_LEVEL_WARNING,

stopOnTerminate: false,
startOnBoot: true,

maxRecordsToPersist: 1,

url: API.userBackgroundGeolocationPingUrl(),
authorization: {
strategy: 'JWT',
accessToken,
refreshToken,
expires,
refreshUrl: `${API.refreshTokenUrl()}?fromBackgroundGeolocation=1`,
refreshPayload: {
refreshToken: '{refreshToken}',
},
},
});
return backgroundGeolocationReady;
};

const BackgroundGolocationProvider = ({ children }) => {
const { user } = useContext(UserContext);

Expand All @@ -25,33 +61,31 @@ const BackgroundGolocationProvider = ({ children }) => {
const [logs, setLogs] = useState(null);

useEffect(() => {
if (user == null)
return;

const locationSubscriber = BackgroundGeolocation.onLocation(() => {}, () => {});

const motionChangeSubscriber = BackgroundGeolocation.onMotionChange(() => {});

const activityChangeSubscriber = BackgroundGeolocation.onActivityChange(() => {});

const authorizationChangeSubscriber = BackgroundGeolocation.onAuthorization((event) => {
if (event.success)
console.log('[authorization] SUCCESS: ', event.response);
else
console.error('[authorization] ERROR: ', event.error);
});

initializeBackgroundGeolocation().catch((error) => {
console.error('Background geolocation loading error', error);
});

return () => {
locationSubscriber.remove();
motionChangeSubscriber.remove();
activityChangeSubscriber.remove();
authorizationChangeSubscriber.remove();
};
}, [user]);
}, []);

useEffect(() => {
if (user == null)
return;

initializeBackgroundGeolocation().catch((error) => {
console.error('Background geolocation loading error', error);
});
}, [initializeBackgroundGeolocation, user]);

useEffect(() => {
if (!initialized)
Expand All @@ -65,7 +99,7 @@ const BackgroundGolocationProvider = ({ children }) => {
BackgroundGeolocation.stop();
}, [backgroundGeolocationEnabled, initialized]);

const initializeBackgroundGeolocation = async () => {
const initializeBackgroundGeolocation = useCallback(async () => {
if (initialized === true)
return;

Expand All @@ -82,43 +116,9 @@ const BackgroundGolocationProvider = ({ children }) => {

log(`Initialized successfully (started : ${enable})`);
setInitialized(true);
};

const setupBackgroundGeolocation = async (authTokens) => {
const { accessToken, refreshToken, expires } = authTokens;
}, [enableAfterInit, initialized]);

const backgroundGeolocationReady = await BackgroundGeolocation.ready({
desiredAccuracy: BackgroundGeolocation.DESIRED_ACCURACY_NAVIGATION,
useSignificantChangesOnly: true,

logLevel: BackgroundGeolocation.LOG_LEVEL_WARNING,

stopOnTerminate: false,
startOnBoot: true,

maxRecordsToPersist: 1,

url: API.userBackgroundGeolocationPingUrl(),
authorization: {
strategy: 'JWT',
accessToken,
refreshToken,
expires,
refreshUrl: `${API.refreshTokenUrl()}?fromBackgroundGeolocation=1`,
refreshPayload: {
refreshToken: '{refreshToken}',
},
},
backgroundPermissionRationale: {
title: 'Autorise la géolocalisation en arrière-plan',
message: 'Il est conseillé d\'activer la géolocalisation en arrière-plan pour que tu puisses profiter pleinement de ton application. ',
positiveAction: 'Autoriser',
},
});
return backgroundGeolocationReady;
};

const setBackgroundGeolocationEnabled = async (enabled = false) => {
const setBackgroundGeolocationEnabled = useCallback(async (enabled = false) => {
try {
if (enabled) {
await BackgroundGeolocation.requestPermission();
Expand All @@ -132,13 +132,15 @@ const BackgroundGolocationProvider = ({ children }) => {
log('Permission granting failed', error);
_setBackgroundGeolocationEnabled(false);
}
};
}, [initializeBackgroundGeolocation, user]);

const value = useMemo(() => ({
backgroundGeolocationEnabled,
setBackgroundGeolocationEnabled,
}), [backgroundGeolocationEnabled, setBackgroundGeolocationEnabled]);

return (
<BackgroundGeolocationContext.Provider value={{
backgroundGeolocationEnabled,
setBackgroundGeolocationEnabled,
}}>
<BackgroundGeolocationContext.Provider value={value}>
{children}
{logs != null && (
<View style={{ ...StyleSheet.absoluteFillObject, backgroundColor: 'rgba(0,0,0,0.8)', ...Styles.center }}>
Expand Down
Loading