react-native#AsyncStorage JavaScript Examples
The following examples show how to use
react-native#AsyncStorage.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Storage.js From RRWallet with MIT License | 6 votes |
storage = new Storage({
// 最大容量,默认值1000条数据循环存储
size: 1000,
// 存储引擎:对于rn使用asyncstorage,对于web使用window.localstorage
// 如果不指定则数据只会保存在内存中,重启后即丢失
storageBackend: AsyncStorage,
// 数据过期时间,默认一整天(1000 * 3600 * 24 毫秒),设为null则永不过期
defaultExpires: null,
// 读写时在内存中缓存数据。默认启用。
enableCache: true,
})
Example #2
Source File: Database.js From hugin-mobile with GNU Affero General Public License v3.0 | 6 votes |
export async function haveWallet() {
try {
const value = await AsyncStorage.getItem(Config.coinName + 'HaveWallet');
if (value !== null) {
return value === 'true';
}
return false;
} catch (error) {
reportCaughtException(error);
Globals.logger.addLogMessage('Error determining if we have data: ' + error);
return false;
}
}
Example #3
Source File: AppNavigator.js From iitj-canteen with GNU General Public License v3.0 | 6 votes |
StackNavigator = createStackNavigator(
{
IntroScreen: IntroScreen,
SplashScreen: SplashScreen,
LoginFlow: SigninScreen,
MainFlow: Drawer
},
{
initialRouteName: AsyncStorage.getItem('FirstTimeUser') ? 'SplashScreen' : 'IntroScreen',
headerMode: 'none'
}
)
Example #4
Source File: StartupScreen.js From SocialApp-React-Native with MIT License | 6 votes |
StartupScreen = props => {
const dispatch = useDispatch();
useEffect(() => {
const tryLogin = async () => {
const userData = await AsyncStorage.getItem('userData');
if (!userData) {
// props.navigation.navigate('Auth');
dispatch(authActions.setDidTryAutoLogin());
return;
}
const transformedData = JSON.parse(userData);
const { token, user } = transformedData;
// props.navigation.navigate('Shop');
dispatch(authActions.authenticate(user, token));
};
tryLogin();
}, [dispatch])
return (
<View style={styles.screen}>
<ActivityIndicator size="large" color={Colors.primary} />
</View>
);
}
Example #5
Source File: ReduxPersist.js From gDoctor with MIT License | 6 votes |
REDUX_PERSIST = {
active: true,
reducerVersion: '1.0',
storeConfig: {
key: 'primary',
storage: AsyncStorage,
// Reducer keys that you do NOT want stored to persistence here.
blacklist: ['login', 'search', 'nav'],
// Optionally, just specify the keys you DO want stored to persistence.
// An empty array means 'don't store any reducers' -> infinitered/ignite#409
// whitelist: [],
transforms: [immutablePersistenceTransform]
}
}
Example #6
Source File: api.js From react-native-expo-starter-kit with MIT License | 6 votes |
/**
* Request Interceptor
*/
axios.interceptors.request.use(
async (inputConfig) => {
const config = inputConfig;
// Check for and add the stored Auth Token to the header request
let token = '';
try {
token = await AsyncStorage.getItem('@Auth:token');
} catch (error) {
/* Nothing */
}
if (token) {
config.headers.common.Authorization = `Bearer ${token}`;
}
return config;
},
(error) => {
throw error;
},
);
Example #7
Source File: store.js From atendimento-e-agilidade-medica-AAMed with MIT License | 6 votes |
StoreProvider = ({ children }) => {
const [state, setState] = useState({
rehydrated: false,
});
// Este é o processo para recuperar o token e usuário logado do Storage do dispositivo quando ele reinicia a aplicação
// O método pega os dados seta o estado pegando tudo o que tinha antes o conteudo do data
// e atualizando a flag rehydrated para true dizendo que o processo foi concluído
const rehydrated = async () => {
const data = await AsyncStorage.getItem('store');
setState(prev => ({
...prev,
...(data && JSON.parse(data)),
rehydrated: true,
}));
};
// A função será executada quando o usuário abrir a aplicação, por isso usa-se o useEffect
useEffect(() => {
rehydrated();
}, []);
// Nesse useEffect poderia ser feito um tratamento de erro
// já que tanto set quanto getItem são assíncronos(falltolerance)
useEffect(() => {
AsyncStorage.setItem('store', JSON.stringify(state));
}, [state]);
return (
<StoreContext.Provider value={[state, setState]}>
{children}
</StoreContext.Provider>
);
}
Example #8
Source File: AuthSaga.js From iitj-canteen with GNU General Public License v3.0 | 6 votes |
function* injectToken(token) {
try {
yield call(setAxiosHeader, token);
yield call(healthCheck);
yield call(AsyncStorage.setItem, 'token', token);
yield put(AuthActionTypes.loadToken(token));
NavigationService.navigateAndReset('MainFlow');
} catch ({ message = 'Snap :(' }) {
yield put(AuthActionTypes.error(message));
yield call(revokeToken);
}
}
Example #9
Source File: cache.js From Done-With-It with MIT License | 6 votes |
store = async (key, value) => {
try {
const item = {
value,
timestamp: Date.now(),
};
await AsyncStorage.setItem(prefix + key, JSON.stringify(item));
} catch (error) {
console.log(error);
}
}
Example #10
Source File: device.js From RRWallet with MIT License | 6 votes |
/**
* 请用getDeviceId
*/
async installID() {
if (installID) {
return installID;
}
try {
installID = await AsyncStorage.getItem(DEVICE_ID_KEY);
if (!installID) {
installID = this.generateUUID();
AsyncStorage.setItem(DEVICE_ID_KEY, installID);
return installID;
}
} catch (error) {}
return installID;
}
Example #11
Source File: AuthSaga.js From iitj-canteen with GNU General Public License v3.0 | 6 votes |
export function* fetchUser() {
try {
yield put(AuthActionTypes.loadingUserInfo());
const token = yield call(AsyncStorage.getItem, 'token');
if (token) {
yield call(injectToken, token);
} else {
const { idToken = null } = yield silentSignIn();
if (idToken) {
yield call(injectToken, idToken);
} else {
yield call(revokeToken);
}
}
} catch ({ message = 'Snap :(' }) {
yield call(revokeToken);
yield put(AuthActionTypes.error(message));
}
}
Example #12
Source File: index.js From react-native-expo-starter-kit with MIT License | 5 votes |
persistPlugin = createPersistPlugin({ version: 2, storage: AsyncStorage, blacklist: [], })
Example #13
Source File: IntroScreen.js From iitj-canteen with GNU General Public License v3.0 | 5 votes |
IntroScreen = ({ navigation }) => {
const renderNextButton = () => {
return (
<View style={styles.buttonCircle}>
<Icon name="arrow-right" color="rgba(255, 255, 255, .9)" size={24} />
</View>
);
};
const renderDoneButton = () => {
return (
<View style={styles.buttonCircle}>
<Icon name="check" color="rgba(255, 255, 255, .9)" size={24} />
</View>
);
};
const renderItem = ({ item }) => {
return (
<View style={{ ...styles.parent, backgroundColor: item.backgroundColor }}>
<Text style={{ fontSize: 20 }}>{item.title}</Text>
<Text style={{ fontSize: 20 }}>{item.text}</Text>
</View>
);
};
const setFirstTimeUser = async () => {
try {
await AsyncStorage.setItem('FirstTimeUser', 'NO');
navigation.navigate('MainFlow');
} catch (e) {
console.error(e);
}
};
return (
<AppIntroSlider
renderDoneButton={renderDoneButton}
renderNextButton={renderNextButton}
renderItem={renderItem}
data={slides}
onDone={setFirstTimeUser}
/>
);
}
Example #14
Source File: index.js From duofolio with GNU General Public License v3.0 | 5 votes |
persistConfig = {
key: 'root',
storage: AsyncStorage,
migrate: createMigrate(migrations, { debug: false })
}
Example #15
Source File: Database.js From hugin-mobile with GNU Affero General Public License v3.0 | 5 votes |
export async function setHaveWallet(haveWallet) {
try {
await AsyncStorage.setItem(Config.coinName + 'HaveWallet', haveWallet.toString());
} catch (error) {
reportCaughtException(error);
Globals.logger.addLogMessage('Failed to save have wallet status: ' + error);
}
}
Example #16
Source File: i18n.js From Legacy with Mozilla Public License 2.0 | 5 votes |
AsyncStorage.getItem('LANG',(e,r)=>{
if(r==="en-US") {
i18n.changeLanguage('en');
AsyncStorage.setItem('LANG','en');
} else if(r) {
i18n.changeLanguage(r);
}
})
Example #17
Source File: AuthSaga.js From iitj-canteen with GNU General Public License v3.0 | 5 votes |
function* revokeToken() {
yield call(revokeAxiosHeader);
yield call(AsyncStorage.removeItem, 'token');
yield put(AuthActionTypes.deleteToken());
NavigationService.navigateAndReset('LoginFlow');
}
Example #18
Source File: HowYouFeel.js From ovuli with MIT License | 5 votes |
HowYouFeel = () => {
const emoticons = [neutral, happy, cry, fearful, love_hearts, tired_face, unamused, disappointed];
saveData = async item => {
const emotionList = [
'neutral',
'happy',
'cry',
'fearful',
'love_hearts',
'tired_face',
'unamused',
'disappointed',
];
let emotion = emotionList[item];
const date = new Date();
try {
AsyncStorage.setItem('emotion', emotion);
AsyncStorage.setItem('timestamp', date.toISOString());
} catch (error) {
console.log('Error saving data', error);
}
};
return (
<View style={styles.container}>
<View style={styles.cycleText}>
<Text style={styles.textStyle_bold}>How are</Text>
<Text style={styles.textStyle_normal}>you feeling?</Text>
</View>
<View style={styles.emoji}>
<FlatList
data={emoticons}
horizontal={true}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item, index }) => (
<TouchableOpacity id={index} onPress={() => saveData(index)}>
<Image style={styles.image} source={item} />
</TouchableOpacity>
)}
/>
</View>
</View>
);
}
Example #19
Source File: auth.js From SocialApp-React-Native with MIT License | 5 votes |
logout = () => {
AsyncStorage.removeItem('userData');
return {
type: LOGOUT
};
}
Example #20
Source File: index.js From discovery-mobile-ui with MIT License | 5 votes |
createStore = (authentication) => {
const { baseUrl, tokenResponse: { accessToken, idToken } } = authentication;
const fhirClient = new FhirClient(baseUrl, accessToken, idToken);
const epicMiddleware = createEpicMiddleware({
dependencies: {
fhirClient,
},
});
const { patientId } = fhirClient;
const rootReducer = combineReducers({
resources: flattenedResourcesReducer,
associations: associationsReducer,
activeCollectionId: activeCollectionIdReducer,
collections: collectionsReducer,
creatingCollection: isCreatingNewCollectionReducer,
});
const persistReducerConfig = {
version: '0.1.0',
key: `root-${patientId}`,
storage: AsyncStorage,
whitelist: ['activeCollectionId', 'collections', 'creatingCollection'],
};
const store = configureStore({
reducer: persistReducer(persistReducerConfig, rootReducer),
middleware: compose([
thunk,
epicMiddleware,
// routerMiddleware(history), // < e.g.: other middleware
]),
devTools: {
serialize: true, // See: https://github.com/zalmoxisus/redux-devtools-extension/blob/master/docs/API/Arguments.md#serialize
},
});
epicMiddleware.run(rootEpic);
const callback = () => {
// callback function will be called after rehydration is finished.
};
const persistConfig = {
// manualPersist: true,
};
const persistor = persistStore(store, persistConfig, callback);
return {
store,
persistor,
};
}
Example #21
Source File: index.js From Legacy with Mozilla Public License 2.0 | 5 votes |
setCode = (data,noUpdate) => async (dispatch, getState) => {
if(!noUpdate) await AsyncStorage.setItem('CODE',data);
dispatch(setCode_(data));
}
Example #22
Source File: list.js From perform-2020-hotday with Apache License 2.0 | 5 votes |
export default function MovieList(props) {
const [ movies, setMovies ] = useState([]);
let token = null;
const getData = async () => {
token = await AsyncStorage.getItem('MR_Token');
if (token) {
getMovies();
} else {
props.navigation.navigate("Auth")
}
};
useEffect(() => {
getData();
}, []);
const getMovies = () => {
console.log(token);
fetch(`http://www.dynatraceworkshops.com:8079/api/movies/`, {
method: 'GET',
headers: {
'Authorization': `Token ${token}`
}
})
.then( res => res.json())
.then( jsonRes => setMovies(jsonRes))
.catch( error => console.log(error));
}
const movieclicked = (movie) => {
props.navigation.navigate("Detail", {movie: movie, title: movie.title, token: token})
}
return (
<View>
<Image source={require('../assets/MR_logo.png')}
style={{width: '100%', height: 135, paddingTop: 30}}
resizeMode="contain"/>
<FlatList
data={movies}
renderItem={({item}) => (
<TouchableOpacity onPress={() => movieclicked(item)}>
<View style={styles.item}>
<Text style={styles.itemText}>{item.title}</Text>
</View>
</TouchableOpacity>
)}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
Example #23
Source File: StreamClient.js From haven with MIT License | 5 votes |
async initializeStream(profile, followings = [], isFirst = false) {
const { peerID } = profile;
let tokens;
let savedTokens;
this.authHolder = new StreamAuth(peerID);
let challengeHeaderCacheWasInvalid = false;
try {
Reactotron.log('cache - request for create stream user', new Date());
await this.authHolder.initStreamClient();
await this.createUser(profile);
Reactotron.log('cache - request finished for stream client init', new Date());
} catch (_) {
challengeHeaderCacheWasInvalid = true;
Reactotron.log('no cache - request for create stream user', new Date());
await this.authHolder.initStreamClient(true);
await this.createUser(profile);
Reactotron.log('no cache - request finished for stream client init', new Date());
}
try {
if (challengeHeaderCacheWasInvalid) {
throw new Error('Challenge Header Cache was invalid, refreshing stream tokens...');
}
savedTokens = await AsyncStorage.getItem('streamTokens');
if (!savedTokens) {
throw new Error('Saved Token is null')
}
tokens = JSON.parse(savedTokens);
Reactotron.log('restored saved token', savedTokens);
} catch (_) {
Reactotron.log('requesting stream token', new Date());
tokens = await this.authHolder.getStreamToken();
AsyncStorage.setItem('streamTokens', JSON.stringify(tokens));
Reactotron.log('request finished for stream token', new Date());
}
if (isFirst) {
Reactotron.log('request for follow many', new Date());
this.authHolder.followMany(followings);
}
this.tokens = tokens;
const { activityToken, feedToken, reactionToken, followToken } = tokens;
this.activityClient = stream.connect(STREAM_API_KEY, activityToken, STREAM_APP_ID, {'location': 'us-east'});
this.feedClient = stream.connect(STREAM_API_KEY, feedToken, STREAM_APP_ID, {'location': 'us-east'});
this.followClient = stream.connect(STREAM_API_KEY, followToken, STREAM_APP_ID, {'location': 'us-east'});
this.followFeed = this.followClient.feed('user', peerID, followToken);
this.localFeed = this.feedClient.feed('posts', peerID, feedToken);
this.feed = this.feedClient.feed('user', peerID, feedToken);
this.globalFeed = this.feedClient.feed('user', 'all', feedToken);
this.notificationFeed = this.feedClient.feed('notifications', peerID, feedToken);
this.socketClient = stream.connect(STREAM_API_KEY, null, STREAM_APP_ID, {'location': 'us-east'});
Reactotron.log('connected to stream', new Date());
this.initDone = true;
}
Example #24
Source File: CustomDrawerContent.js From atendimento-e-agilidade-medica-AAMed with MIT License | 5 votes |
export default function CustomDrawerContent(props) {
const [, { logout }] = useAuth();
const [user, setUser] = useState(null || '');
// A função getUserLogged recupera os dados do usuário por meio de uma Promise
// que é executada assim que o componente e montado
useEffect(() => {
function getUserLogged() {
// O uso da Promise + setTmeout foi necessário pois leva um tempo até os dados do AsyncStorage sejam recuperados
return new Promise((resolve, reject) => {
setTimeout(() => {
// A função resolve() irá conter os dados do usuário após 2s definidos no setTimeout()
resolve(AsyncStorage.getItem('store'));
}, 2000);
});
}
getUserLogged()
.then(data => {
// Para acessar os dados recuperados é usado o .then()
// Como os dados armazenados estão em formato de string, é utilizado o JSON.parse() para tranforma-los em objeto
const dataParse = JSON.parse(data);
// Após esse processo teremos um objeto que terá dentro outro objeto "auth", nele está os dados do usuário além do token
// Como só é necessário apenas o usuário, o estado é setado apenas com os dados do mesmo (id, nome, bio, etc.)
setUser(dataParse.auth.user);
})
.catch(err => console.log(err)); // Por fim é usado um .catch() para tratar algum erro
}, []);
return (
<DrawerContentScrollView {...props}>
<View style={styles.topDrawer}>
<View style={styles.viewAvatar}>
<Avatar
avatarStyle={styles.avatarStyle}
containerStyle={styles.avatarContainerStyle}
onPress={() => props.navigation.navigate('EditProfile')}
activeOpacity={0.7}
size="medium"
rounded
title={user ? JSON.stringify(user.name[0]) : 'a'}
/>
</View>
<View style={styles.viewDados}>
<Text style={styles.nameUser}>{user.name}</Text>
<Text style={styles.bioUser}>{user.bio}</Text>
</View>
</View>
<DrawerItemList {...props} />
<View style={styles.separator} />
<DrawerItem
onPress={logout}
label="SAIR"
style={styles.drawerItem}
labelStyle={styles.drawerItemLabel}
icon={() => <Feather name="log-out" size={20} color="#E53935" />}
/>
</DrawerContentScrollView>
);
}
Example #25
Source File: index.js From Legacy with Mozilla Public License 2.0 | 5 votes |
levelSelect = (data,noUpdate) => async (dispatch, getState) => {
if(!noUpdate) await AsyncStorage.setItem('LEVEL_SELECT',stringify({...getState().clanLevelSelect,...data}));
dispatch(levelSelect_(data));
}
Example #26
Source File: App.js From salyd with GNU General Public License v3.0 | 5 votes |
App = () => {
const [isReady, setIsReady] = useState(false);
const [initialScreen, setInititalScreen] = useState("Onboarding");
const [loaded] = useFonts({
'ProductSans': require('./assets/fonts/Product_Sans_Regular.ttf'),
'ProductSansItalic': require('./assets/fonts/Product_Sans_Italic.ttf'),
'ProductSansBold': require('./assets/fonts/Product_Sans_Bold.ttf'),
'ProductSansBoldItalic': require('./assets/fonts/Product_Sans_Bold_Italic.ttf'),
'DMSansBold': require('./assets/fonts/DMSans-Bold.ttf'),
'DMSansRegular': require('./assets/fonts/DMSans-Regular.ttf'),
'PTSans': require('./assets/fonts/Product_Sans_Regular.ttf'),
'PTSansBold': require('./assets/fonts/Product_Sans_Bold.ttf')
});
console.disableYellowBox = true;
useEffect(() => {
const checkToken = async () => {
const user = await AsyncStorage.getItem('user');
console.log(user)
if (user) {
setInititalScreen("MainApp");
}
setIsReady(true);
}
checkToken()
}, []);
if (!isReady || !loaded) {
return null;
}
return (
<GlobalProvider>
<NavigationContainer>
<StatusBar backgroundColor="white" />
<Stack.Navigator headerMode="none" initialRouteName={initialScreen}>
<Stack.Screen name="SignUp" component={SignUp} />
<Stack.Screen name="Onboarding" component={Onboarding} />
<Stack.Screen name="Splash" component={Splash} />
<Stack.Screen name="Login" component={Login} />
<Stack.Screen name="MainApp" component={MainApp} />
<Stack.Screen name="Guest" component={Guest} />
<Stack.Screen name="ForgotPassword" component={ForgotPassword} />
</Stack.Navigator>
</NavigationContainer>
</GlobalProvider>
)
}
Example #27
Source File: index.js From Legacy with Mozilla Public License 2.0 | 5 votes |
userBookmarks = (data,noUpdate) => async (dispatch, getState) => {
if(!noUpdate) await AsyncStorage.setItem('USER_BOOKMARKS',stringify(data));
dispatch(userBookmarks_(data));
}
Example #28
Source File: LeftDays.js From ovuli with MIT License | 4 votes |
LeftDays = () => {
const [name, setName] = useState('');
const [avgCycle, setAvgCycle] = useState(0);
const [lastPeriod, setLastPeriod] = useState(0);
const [ovulationDaysLeft, setOvulationDaysLeft] = useState(0);
const [periodDaysLeft, setPeriodDaysLeft] = useState(0);
const [progress, setProgress] = useState(0);
const [greeting, setGreeting] = useState('');
// Fetches name of the user from AsyncStorage
const getName = async () => {
try {
let user_name = await AsyncStorage.getItem('Name');
setName(user_name);
} catch (error) {
console.log('Error fetching name in LeftDays', error);
}
};
useEffect(() => {
getName(); // Fetching name of the user
(async function() {
const avgCycle = await AsyncStorage.getItem('AvgPeriod');
const lastPeriod = await AsyncStorage.getItem('lastPeriod');
setAvgCycle(avgCycle);
setLastPeriod(lastPeriod);
})();
const ovuliResult = calculateOvuli({ lastDate: lastPeriod }, { averageCycle: avgCycle });
const today = moment();
const hour = today.hour();
if (hour >= 4 && hour < 12) setGreeting('Good Morning');
else if (hour >= 12 && hour < 19) setGreeting('Good Evening');
else setGreeting('Good Night');
let ovulationDate = moment([
today.year(),
ovuliResult['approximateOvulationDate']['month'],
ovuliResult['approximateOvulationDate']['day'],
]);
let periodDate = moment([
today.year(),
ovuliResult['nextPeriodDate']['month'],
ovuliResult['nextPeriodDate']['day'],
]);
setOvulationDaysLeft(ovulationDate.diff(today, 'days'));
setPeriodDaysLeft(periodDate.diff(today, 'days'));
const progress = 100 - (Math.ceil(periodDaysLeft) / 40) * 100;
setProgress(progress);
});
const contentCircle = () => {
return (
<View style={{ alignItems: 'center' }}>
<Text style={{ fontFamily: 'PT-Sans', fontWeight: '700', fontSize: 25 }}>
{parseInt(periodDaysLeft)}
</Text>
<Text style={{ fontFamily: 'PT-Sans', marginTop: 8, fontSize: 16 }}>Days to Period</Text>
<Text
style={{
fontFamily: 'PT-Sans',
fontWeight: '700',
marginTop: 25,
fontSize: 25,
fontSize: 25,
}}
>
{parseInt(ovulationDaysLeft)}
</Text>
<Text style={{ fontFamily: 'PT-Sans', marginTop: 8, fontSize: 16 }}>Days to Ovulation</Text>
</View>
);
};
return (
<View style={styles.container}>
<StatusBar hidden={true} />
<LinearGradient
colors={['#F78161', '#F65863']}
start={[0.2, 0.3]}
end={[0.2, 0.6]}
style={styles.linearGradient}
>
<View style={styles.text}>
<Text style={{ fontFamily: 'PT-Sans', fontSize: 28 }}>{greeting}</Text>
<Text style={{ fontFamily: 'PT-Sans', fontWeight: '700', fontSize: 30, marginTop: 25 }}>
{name}
</Text>
</View>
<View style={styles.circle}>
<AnimatedCircularProgress
size={Dimensions.get('window').width - 75}
width={18}
fill={progress}
tintColor="#C5DEFF"
lineCap={'butt'}
style={styles.circleContainer}
>
{fill => contentCircle()}
</AnimatedCircularProgress>
</View>
</LinearGradient>
</View>
);
}
Example #29
Source File: Menu.js From salyd with GNU General Public License v3.0 | 4 votes |
Menu = (props) => {
const { token, globalRoomId, globalTableId, updateOrder, order, localroomId, restro } = useContext(
GlobalContext
);
const [menu, setMenu] = useState([]);
const [permission, setPermission] = useState("");
const [user, setUser] = useState({});
const [search, setSearch] = useState("");
const [data_temp, setdata_temp] = useState([]);
useEffect(() => {
const getPermission = async () => {
const userId = await AsyncStorage.getItem("userId");
console.log(token, "token from Menu.js");
//Fetching permission role for logged in user using token
if (token) {
fetch(`${apiUrl}/permission/get`, {
headers: {
Authorization: "Bearer " + token,
},
})
.then((res) => res.json())
.then((data) => {
//Setting user details
setUser(data.user);
//Setting user permission
console.log(data.user.role, "logged in user");
setPermission(data.user.role);
})
.catch((err) => {
console.log(err);
});
}
//Fetching permission role for guest user using userId
else if (userId) {
fetch(`${apiUrl}/permission/get`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
id: userId,
}),
})
.then((res) => res.json())
.then((data) => {
//Setting user details
setUser(data.user);
console.log(data.user.role, "guest user");
//Setting user permissions
setPermission(data.user.role);
});
}
};
const getMenu = async () => {
const roomId = globalRoomId;
console.log(roomId, "roomId");
//Fetching menu for logged in user
if (token) {
fetch(`${apiUrl}/menu`, {
headers: {
Authorization: "Bearer " + token,
},
})
.then((res) => res.json())
.then((data) => {
//Providing the rooms with unique id
socket.emit("joinRoom", user.name, globalTableId);
//Initializing the counter
data.tableOf.menu.map((elem) => {
elem.count = 0;
});
//Setting the menu
setMenu(data.tableOf.menu);
setdata_temp(data.tableOf.menu);
})
.catch((err) => {
console.log(err);
});
}
//Fetching menu for guest user using roomId stored in async storage
else if (roomId) {
fetch(`${apiUrl}/menu/guest`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
roomId: roomId,
}),
})
.then((res) => res.json())
.then((data) => {
//Providing the rooms with unique id
socket.emit("joinRoom", user.name, globalTableId);
//Initializing the counter
data.tableOf.menu.map((elem) => {
elem.count = 0;
});
//Setting the menu
setMenu(data.tableOf.menu);
setdata_temp(data.tableOf.menu);
})
.catch((err) => {
console.log(err);
});
}
};
getPermission();
getMenu();
}, []);
console.log(restro, "restro global state")
//Emitting the joinRoom event to the server
//Event emitted @Server
//Increasing the no of items
const incrementCounter = (id, index) => {
if (id === menu[index]._id) {
let newMenu = [...menu];
newMenu[index].count += 1;
setMenu(newMenu);
//Emitting the counter(increment) change event @Sever
socket.emit("countChange", menu, globalTableId);
}
};
//Decreasing the no of items
const decrementCounter = (id, index) => {
if (id === menu[index]._id) {
let newMenu = [...menu];
if (newMenu[index].count > 0) {
newMenu[index].count -= 1;
} else {
newMenu[index].count = 0;
}
setMenu(newMenu);
//Emitting the counter(decrement) change event @Sever
socket.emit("countChange", menu, globalTableId);
}
};
//Placing order
const orderPlaced = () => {
updateOrder({
orderId: globalTableId,
menu
})
props.navigation.push("Checkout");
// socket.emit('orderPlaced',"Hi");
};
//Listening for the menuChange event from @Sever
socket.on("menuChange", (menu) => {
setMenu(menu);
});
const renderList = (item, index) => (
<View style={styles.item}>
<View style={styles.content}>
<Text style={styles.name}>{item.item}</Text>
<Text style={styles.desc}>Lorem ipsum, quos</Text>
<View style={styles.price}>
<Text style={styles.textPrice}>₹ {item.price}</Text>
</View>
</View>
<View style={styles.counterContainer}>
<TouchableOpacity
onPress={() => decrementCounter(item._id, index)}
disabled={permission === "view" ? true : false}
>
<View style={styles.counter}>
<Text style={styles.textCounter}>-</Text>
</View>
</TouchableOpacity>
<Text style={styles.main_count}> {menu[index].count} </Text>
<TouchableOpacity
onPress={() => incrementCounter(item._id, index)}
disabled={permission === "view" ? true : false}
>
<View style={styles.counter}>
<Text style={styles.textCounter}>+</Text>
</View>
</TouchableOpacity>
</View>
</View>
);
const _search = (text) => {
let data = [];
data_temp.map(function (value) {
if (value.item.indexOf(text) > -1) {
data.push(value);
}
});
setMenu(data);
setSearch(text);
};
const ItemSeparatorComponent = () => {
return (
<View
style={{
height: 10,
}}
/>
);
};
return (
<View style={styles.container}>
<Header navigation={props.navigation}>Menu</Header>
<Searchbar
style={{
margin: 15,
borderRadius: 40,
}}
placeholder="Search"
onChangeText={_search}
value={search}
/>
<View style={styles.flatList}>
<FlatList
data={menu}
renderItem={({ item, index }) => {
return renderList(item, index);
}}
keyExtractor={(item) => item._id}
ItemSeparatorComponent={() => ItemSeparatorComponent()}
showsVerticalScrollIndicator={true}
></FlatList>
</View>
{permission === "admin" ? (
<View style={{
justifyContent: "center",
alignItems: "center",
marginBottom: 20
}}>
<Button
onPressFunction={() => orderPlaced()}
>Give order</Button>
</View>
) : null}
</View>
);
}