Skip to content

Instantly share code, notes, and snippets.

@ScreamZ
Last active November 1, 2019 18:49
Show Gist options
  • Save ScreamZ/5d9fe683050a07cc6cd79e860daa035b to your computer and use it in GitHub Desktop.
Save ScreamZ/5d9fe683050a07cc6cd79e860daa035b to your computer and use it in GitHub Desktop.
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