Last active
November 1, 2019 18:49
-
-
Save ScreamZ/5d9fe683050a07cc6cd79e860daa035b to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import AsyncStorage from "@react-native-community/async-storage"; | |
import to from "await-to-js"; | |
import { useCallback, useEffect, useState } from "react"; | |
enum CountrySelectionStatus { | |
Loading = "LOADING", | |
NotChosen = "NOT_CHOSEN", | |
Skipped = "SKIPPED", | |
} | |
enum AsyncStorageKeys { | |
UserFavoriteCountry = "UserFavoriteCountry", | |
} | |
export interface UseFavoriteContext { | |
favoriteCountry: string | CountrySelectionStatus; | |
setFavoriteCountry: (country: string) => Promise<void>; | |
} | |
/** | |
* Get and save user favorite information. | |
* | |
* @export | |
* @returns {UseFavoriteContext} | |
*/ | |
export function useFavoriteCountry(): UseFavoriteContext { | |
const setFavoriteCountry = useCallback(async (countryCode: string | CountrySelectionStatus) => { | |
await AsyncStorage.setItem(AsyncStorageKeys.UserFavoriteCountry, countryCode); | |
setFavoriteCtx(prev => ({ | |
...prev, | |
favoriteCountry: countryCode, | |
})); | |
}, []); | |
// State | |
const [favoriteCtx, setFavoriteCtx] = useState<UseFavoriteContext>({ | |
favoriteCountry: CountrySelectionStatus.Loading, | |
setFavoriteCountry, | |
}); | |
// Read in memory data on load. | |
useEffect(() => { | |
async function initializeStateFromAsyncStorage() { | |
const [err, favoriteCountry] = await to(AsyncStorage.getItem(AsyncStorageKeys.UserFavoriteCountry)); | |
if (err || favoriteCountry === CountrySelectionStatus.NotChosen) { | |
setFavoriteCtx(prev => ({ | |
...prev, | |
favoriteCountry: CountrySelectionStatus.NotChosen, | |
})); | |
return; | |
} | |
setFavoriteCtx(prev => ({ | |
...prev, | |
favoriteCountry: favoriteCountry!, | |
})); | |
} | |
initializeStateFromAsyncStorage(); | |
}, []); | |
return favoriteCtx; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment