Skip to content

Commit

Permalink
Fix error with a race condition in logging
Browse files Browse the repository at this point in the history
  • Loading branch information
jtklein committed Sep 3, 2024
1 parent 6d92153 commit 512a232
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions components/Navigation/hooks/useAppLog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,19 @@ import { LogLevels, logToApi } from "../../../utility/apiCalls";
import taxonIds from "../../../utility/dictionaries/taxonDict";
import realmConfig from "../../../models/index";

const runOncePerMonth = async ( callback: () => void ) => {
const executeInNewMonth = async ( callback: () => void, keySubstring: string ) => {
const storageKeyBase = "lastRunMonth";
const storageKey = storageKeyBase + keySubstring;
try {
const lastRun = await AsyncStorage.getItem( "lastRunMonth" );
const lastRun = await AsyncStorage.getItem( storageKey );
const currentMonth = new Date().getMonth();

if ( lastRun === null || parseInt( lastRun, 10 ) !== currentMonth ) {
// Run the function as the month has changed
callback();

// Update the last run month
await AsyncStorage.setItem( "lastRunMonth", currentMonth.toString() );
await AsyncStorage.setItem( storageKey, currentMonth.toString() );
}
} catch ( error ) {
console.error( "Error checking or updating last run month:", error );
Expand Down Expand Up @@ -56,12 +58,12 @@ function useAppLog() {
await logToApi( {
level: LogLevels.INFO,
message: JSON.stringify( achievementsLogState ),
context: "RootStack achievementsState",
context: "RootStack achievementsState v1",
errorType: "0"
} );
};

runOncePerMonth( logBadgesAppState );
executeInNewMonth( logBadgesAppState, "1" );
}, [] );

useEffect( ( ) => {
Expand All @@ -81,12 +83,12 @@ function useAppLog() {
await logToApi( {
level: LogLevels.INFO,
message: JSON.stringify( challengesLogState ),
context: "RootStack challengesState",
context: "RootStack challengesState v1",
errorType: "0"
} );
};

runOncePerMonth( logChallengesAppState );
executeInNewMonth( logChallengesAppState, "2" );
}, [] );

useEffect( ( ) => {
Expand All @@ -104,12 +106,12 @@ function useAppLog() {
await logToApi( {
level: LogLevels.INFO,
message: JSON.stringify( observationsLogState ),
context: "RootStack observationsState",
context: "RootStack observationsState v1",
errorType: "0"
} );
};

runOncePerMonth( logChallengesAppState );
executeInNewMonth( logChallengesAppState, "3" );
}, [] );
}

Expand Down

0 comments on commit 512a232

Please sign in to comment.