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 vote down vote up
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: store.js    From atendimento-e-agilidade-medica-AAMed with MIT License 6 votes vote down vote up
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 #3
Source File: Database.js    From hugin-mobile with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #4
Source File: ReduxPersist.js    From gDoctor with MIT License 6 votes vote down vote up
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 #5
Source File: api.js    From react-native-expo-starter-kit with MIT License 6 votes vote down vote up
/**
 * 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 #6
Source File: cache.js    From Done-With-It with MIT License 6 votes vote down vote up
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 #7
Source File: AppNavigator.js    From iitj-canteen with GNU General Public License v3.0 6 votes vote down vote up
StackNavigator = createStackNavigator(
	{
		IntroScreen: IntroScreen,
		SplashScreen: SplashScreen,
		LoginFlow: SigninScreen,
		MainFlow: Drawer
	},
	{
		initialRouteName: AsyncStorage.getItem('FirstTimeUser') ? 'SplashScreen' : 'IntroScreen',
		headerMode: 'none'
	}
)
Example #8
Source File: StartupScreen.js    From SocialApp-React-Native with MIT License 6 votes vote down vote up
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 #9
Source File: i18n.js    From Legacy with Mozilla Public License 2.0 5 votes vote down vote up
AsyncStorage.getItem('LANG',(e,r)=>{
    if(r==="en-US") {
      i18n.changeLanguage('en');
      AsyncStorage.setItem('LANG','en');
    } else if(r) {
      i18n.changeLanguage(r);
    }
  })
Example #10
Source File: list.js    From perform-2020-hotday with Apache License 2.0 5 votes vote down vote up
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 #11
Source File: StreamClient.js    From haven with MIT License 5 votes vote down vote up
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 #12
Source File: CustomDrawerContent.js    From atendimento-e-agilidade-medica-AAMed with MIT License 5 votes vote down vote up
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 #13
Source File: App.js    From salyd with GNU General Public License v3.0 5 votes vote down vote up
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 #14
Source File: index.js    From duofolio with GNU General Public License v3.0 5 votes vote down vote up
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 vote down vote up
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: index.js    From react-native-expo-starter-kit with MIT License 5 votes vote down vote up
persistPlugin = createPersistPlugin({
  version: 2,
  storage: AsyncStorage,
  blacklist: [],
})
Example #17
Source File: IntroScreen.js    From iitj-canteen with GNU General Public License v3.0 5 votes vote down vote up
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 #18
Source File: HowYouFeel.js    From ovuli with MIT License 5 votes vote down vote up
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 vote down vote up
logout = () => {
    AsyncStorage.removeItem('userData');
    return {
        type: LOGOUT
    };
}
Example #20
Source File: index.js    From discovery-mobile-ui with MIT License 5 votes vote down vote up
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: Settings.js    From Legacy with Mozilla Public License 2.0 4 votes vote down vote up
export default function SettingsScreen({ navigation }) {
  var { t, i18n } = useTranslation();
  var logins = useSelector(i => i.logins);
  var themes = useSelector(i => i.themes);
  var theme = useSelector(i => i.themes[i.theme]);
  var dispatch = useDispatch();
  var { width } = useDimensions().window;

  function setLang(lang) {
    i18n.changeLanguage(lang);
    AsyncStorage.setItem('LANG', lang);
  }

  function logout(user_id) {
    dispatch(removeLogin(user_id))
  }

  var languages = [
    { value: 'cs', label: 'Čeština', flag: "CZ" },
    { value: 'da', label: 'Dansk' },
    { value: 'de', label: 'Deutsch' },
    { value: 'en-GB', label: 'English' },
    { value: 'en', label: 'English (US)' },
    { value: 'fi', label: 'Suomi' },
    { value: 'fr', label: 'Français' },
    { value: 'hu', label: 'Magyar' },
    // {value:'lt',label:'Lietuvių Kalba'},
    { value: 'nl', label: 'Nederlands' },
    { value: 'pt', label: 'Português' },
    // {value:'sv',label:'Svenska'}
  ]

  var themeslist = Object.entries(themes).filter(i => !i[0].startsWith('_')).reverse().map(i=>({
    value: i[1].id,
    label: t(`themes:${i[1].id}`)
  }))

  var baseSettings = useSelector(i => i.settings)
  var [settings, setSettings] = React.useState({});
  function setSetting(option, value) {
    var x = {}
    x[option] = value;
    setSettings({ ...settings, ...x });
  }
  function saveSettings() {
    dispatch(settingsDispatch(settings));
  }
  React.useEffect(() => {
    setSettings(baseSettings);
  }, [baseSettings])



  return (
    <View style={{ flex: 1, backgroundColor: theme.page.bg, justifyContent: 'center', alignItems: 'center' }}>
      <View style={{ flex: 1, width: width > 800 ? "50%" : "100%", padding: 4 }}>
        <Card noPad>
          <ScrollView contentContainerStyle={{ padding: 8 }}>
            {Object.entries(logins).map(user => <View key={user[0]} style={{ padding: 8, flexDirection: "row", alignItems: "center" }}>
              <Image source={{ uri: `https://munzee.global.ssl.fastly.net/images/avatars/ua${Number(user[0]).toString(36)}.png` }} style={{ borderRadius: 16, width: 32, height: 32 }} />
              <View style={{ paddingLeft: 8, flex: 1, alignSelf: "center" }}>
                <Text allowFontScaling={false} style={{ ...font("bold"), fontSize: 16, color: theme.page_content.fg }}>{user[1].username}</Text>
              </View>
              <Button compact={true} mode="contained" color="red" onPress={() => logout(user[0])}>{t('settings:logout')}</Button>
            </View>)}
            <View style={{ flexDirection: "row", flexWrap: "wrap" }}>
              <Button
                mode="contained"
                icon="account-plus"
                backgroundColor={theme.navigation.fg}
                style={theme.page_content.border ? { margin: 4, flex: 1, borderColor: "white", borderWidth: 1 } : { margin: 4, flex: 1 }}
                color={theme.navigation.bg}
                onPress={() => navigation.navigate('Auth')}>
                {t('settings:add_user')}
              </Button>
              {Platform.OS === "web" && <Button
                mode="contained"
                icon="reload"
                backgroundColor={theme.navigation.fg}
                style={theme.page_content.border ? { margin: 4, flex: 1, borderColor: "white", borderWidth: 1 } : { margin: 4, flex: 1 }}
                color={theme.navigation.bg}
                onPress={() => forceReload()}>
                {t('settings:update')}
              </Button>}
            </View>

            <View style={{ padding: 4 }}>
              <Text allowFontScaling={false} style={{ fontSize: 14, lineHeight: 14, marginBottom: -4, ...font(), color: theme.page_content.fg }}>Theme</Text>
              <Dropdown dense={true} mode="outlined" selectedValue={theme.id} onValueChange={i=>dispatch(setTheme(i))}>
                {themeslist.map(i=><DropdownItem label={i.label} value={i.value} />)}
              </Dropdown>
            </View>

            <View style={{ padding: 4 }}>
              <Text allowFontScaling={false} style={{ fontSize: 14, lineHeight: 14, marginBottom: -4, ...font(), color: theme.page_content.fg }}>Language</Text>
              <Dropdown dense={true} mode="outlined" selectedValue={i18n.language} onValueChange={setLang}>
                {languages.map(i=><DropdownItem label={i.label} value={i.value} />)}
              </Dropdown>
            </View>
            {/* <View style={{flexDirection:"row",alignItems:"center",padding:4}}>
              <Switch style={{marginRight: 8}} color={theme.page_content.fg} value={settings.activityV2Beta} onValueChange={(value)=>setSetting("activityV2Beta",!settings.activityV2Beta)} />
              <Text allowFontScaling={false} style={{color:theme.page_content.fg, flex: 1,...font("bold")}}>User Activity Beta</Text>
            </View> */}
            {Platform.OS === "ios" && <View style={{ flexDirection: "row", alignItems: "center", padding: 4 }}>
              <Switch style={{ marginRight: 8 }} color={theme.page_content.fg} value={settings.appleMaps} onValueChange={(value) => setSetting("appleMaps", !settings.appleMaps)} />
              <Text allowFontScaling={false} style={{ color: theme.page_content.fg, flex: 1, ...font("bold") }}>Apple Maps</Text>
            </View>}
            <View>
              {[
                ["clan_level_ind", "Individual"],
                ["clan_level_bot", "Both"],
                ["clan_level_gro", "Group"],
                ["clan_level_0", "No Level"],
                ["clan_level_1", "Level 1"],
                ["clan_level_2", "Level 2"],
                ["clan_level_3", "Level 3"],
                ["clan_level_4", "Level 4"],
                ["clan_level_5", "Level 5"],
                ["clan_level_null", "Empty"]
              ].map(i => <View style={{ padding: 4 }}>
                <Text allowFontScaling={false} style={{ fontSize: 14, lineHeight: 14, marginBottom: -4, ...font(), color: theme.page_content.fg }}>{i[1]}</Text>
                <TextInput
                  dense={true}
                  mode="outlined"
                  theme={{
                    dark: theme.dark,
                    colors: {
                      primary: (settings[i[0]]?.length == 7 && settings[i[0]]?.startsWith('#')) ? whiteOrBlack(settings[i[0]] || "") : theme.page_content.fg,
                      background: (settings[i[0]]?.length == 7 && settings[i[0]]?.startsWith('#')) ? settings[i[0]] : theme.page_content.bg,
                      placeholder: (settings[i[0]]?.length == 7 && settings[i[0]]?.startsWith('#')) ? whiteOrBlack(settings[i[0]] || "") : theme.page_content.fg,
                      text: (settings[i[0]]?.length == 7 && settings[i[0]]?.startsWith('#')) ? whiteOrBlack(settings[i[0]] || "") : theme.page_content.fg
                    }
                  }}
                  placeholder={i[1]}
                  value={settings[i[0]]}
                  onChangeText={text => setSetting(i[0], text)}
                />
              </View>)}
            </View>
            <Button
              mode="contained"
              icon="content-save"
              backgroundColor={theme.navigation.fg}
              style={theme.page_content.border ? { margin: 4, borderColor: "white", borderWidth: 1 } : { margin: 4 }}
              color={theme.navigation.bg}
              onPress={saveSettings}>
              {t('settings:save')}
            </Button>
          </ScrollView>
        </Card>
      </View>
    </View>
  );
}
Example #22
Source File: auth.js    From perform-2020-hotday with Apache License 2.0 4 votes vote down vote up
//ToDo
//import { Dynatrace, Platform } from '@dynatrace/react-native-plugin';

export default function Auth(props) {

  const [ username, setUsername] = useState("");
  const [ password, setPassword] = useState("");
  const [ regView, setRegView] = useState(false);

  useEffect(()=> {
    getData();
  }, [])

  const auth = () => {
    if (regView) {
      fetch(`http://www.dynatraceworkshops.com:8079/api/users/`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ username, password})
      })
      .then( res => res.json())
      .then( res => {
        setRegView(false);
      })
      .catch( error => console.log(error));
    } else {
      fetch(`http://www.dynatraceworkshops.com:8079/auth/`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password})
        })
        .then( res => res.json())
        .then( res => {
          saveData(res.token);
	  //ToDo
          // Dynatrace.identifyUser(username);
          props.navigation.navigate("MovieList");
        })
        .catch( error => {
		console.log(error);
		//ToDo
		// Dynatrce.reportError("Invalid Login", -1);
		}
		);
    }
  };
  const saveData = async (token) => {
    await AsyncStorage.setItem('MR_Token', token)
  }
  const getData = async () => {
    const token = await AsyncStorage.getItem('MR_Token');
    if(token) props.navigation.navigate("MovieList");
  }
  const toggleView = () => {
    setRegView(!regView);
  }

  return (
    <View style={styles.container}>
      <Text style={styles.label}>Username</Text>
      <TextInput 
        style={styles.input}
        placeholder="Username"
        onChangeText={text => setUsername(text)}
        value={username}
        autoCapitalize={'none'}
      />
      <Text style={styles.label}>Password</Text>
      <TextInput 
        style={styles.input}
        placeholder="Password"
        onChangeText={text => setPassword(text)}
        value={password}
        secureTextEntry={true}
        autoCapitalize={'none'}
      />
      <Button onPress={() => auth()} title={regView ? "Register" : "Login"} />
      <TouchableOpacity onPress={() => toggleView()}>
        {regView ? <Text style={styles.viewText}>Already have an account? Go back to login.</Text> : 
        <Text style={styles.viewText}>Don't have an account? Register here.</Text>}
      </TouchableOpacity>
    </View>
  );
}
Example #23
Source File: index.js    From atendimento-e-agilidade-medica-AAMed with MIT License 4 votes vote down vote up
export default function EditProfile({ navigation }) {
  const [id, setId] = useState('');
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [bio, setBio] = useState('');

  useEffect(() => {
    function getUserLogged() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(AsyncStorage.getItem('store'));
        }, 1000);
      });
    }
    getUserLogged()
      .then(data => {
        const dataParse = JSON.parse(data);
        const { _id, name, email, bio } = dataParse.auth.user;
        // console.log(`// ${_id} // ${name} // ${email} // ${bio}`)
        setId(_id);
        setName(name);
        setEmail(email);
        setBio(bio);
      })
      .catch(err => console.log(err));
  }, []);

  async function onSubmit() {
    // PRECISA SAIR E ENTRAR PARA TER AS INFORMAÇÕES ATUALIZADAS
    try {
      await api.put(`/user/${id}`, {
        name,
        email,
        bio,
      });
      // melhorar a mensagem (talvez)
      navigation.navigate('Home');
      Alert.alert(
        'Perfil editado com sucesso!',
        'Faça logout e login para atualizar as informações no perfil'
      );
      // { headers: { Authorization: `Bearer ${token}` } }
      // console.log(id, name, email, bio, "response ", res)
    } catch (error) {
      if (error.response) {
        console.log(error.response.data);
      } else if (error.request) {
        console.log(error.request);
      } else {
        console.log('Error', error.message);
      }
      console.log('Erro fora dos ifs ', error);
    }
  }

  return (
    <>
      <Header navigation={navigation} label={'EDITAR PERFIL'} />
      <EditBox>
        <InputBox>
          <Label>Nome</Label>
          <Input
            placeholder="Vinicius Fernando Piantoni"
            placeholderTextColor="#00000066"
            returnKeyType="next"
            selectionColor="#006bad66"
            onChangeText={e => setName(e)}
            value={name}
          />
        </InputBox>
        <InputBox>
          <Label>E-mail</Label>
          <Input
            placeholder="[email protected]"
            autoCapitalize="none"
            placeholderTextColor="#00000066"
            returnKeyType="next"
            selectionColor="#006bad66"
            onChangeText={e => setEmail(e)}
            value={email}
          />
        </InputBox>
        <InputBox>
          <Label>Bio</Label>
          <Input
            placeholder="Rinite e miopia"
            placeholderTextColor="#00000066"
            returnKeyType="done"
            selectionColor="#006bad66"
            multiline
            onChangeText={e => setBio(e)}
            value={bio}
          />
        </InputBox>
        <MainButton onPress={() => onSubmit()} label="EDITAR" />
      </EditBox>
    </>
  );
}
Example #24
Source File: GlobalState.js    From salyd with GNU General Public License v3.0 4 votes vote down vote up
GlobalProvider = ({ children }) => {
    const [state, dispatch] = useReducer(AppReducer, initialState);

    useEffect(() => {
        async function fetchUser() {
            const user = await retrieveItem('user');
            dispatch({ type: Actions.UPDATE_USER, payload: user });
        }
        async function fetchToken() {
            const token = await AsyncStorage.getItem('token');
            dispatch({ type: Actions.UPDATE_TOKEN, payload: token });
        }
        async function fetchTable() {
            const data = await AsyncStorage.getItem('tableId');
            dispatch({ type: Actions.UPDATE_TABLE_ID, payload: data });
        }
        async function fetchRoom() {
            const data = await AsyncStorage.getItem('roomId');
            dispatch({ type: Actions.UPDATE_ROOM_ID, payload: data });
        }
        fetchUser();
        fetchToken();
        fetchTable();
        fetchRoom();
    }, [])

    const updateUser = (userData) => {
        dispatch({
            type: Actions.UPDATE_USER,
            payload: userData
        });
    }

    const updateToken = (userData) => {
        dispatch({
            type: Actions.UPDATE_TOKEN,
            payload: userData
        });
    }

    const updateTable = (tableId) => {
        dispatch({
            type: Actions.UPDATE_TABLE_ID,
            payload: tableId
        });
    }

    const updateRoom = (roomId) => {
        dispatch({
            type: Actions.UPDATE_ROOM_ID,
            payload: roomId
        });
    }

    const updateOrder = (order) => {
        dispatch({
            type: Actions.UPDATE_ORDER,
            payload: order
        });
    }

    const updateRestro = (restro) => {
        dispatch({
            type: Actions.UPDATE_RESTRO,
            payload: restro
        })
    }

    const changeTheme = () => {
        dispatch({
            type: Actions.CHANGE_THEME,
        })
    }

    return (
        <GlobalContext.Provider
            value={{
                user: state.user,
                token: state.token,
                order: state.order,
                globalTableId: state.tableId,
                globalRoomId: state.roomId,
                restro: state.restro,
                currentTheme: state.currentTheme,
                updateUser,
                updateToken,
                updateTable,
                updateRoom,
                updateOrder,
                updateRestro,
                changeTheme
            }}
        >
            {children}
        </GlobalContext.Provider>
    );
}
Example #25
Source File: ProfilePage.js    From inventory-management-rn with MIT License 4 votes vote down vote up
ProfilePage = ({ navigation }) => {

    const [editMode, toggleEditMode] = useState(false)

    const [firstName, updateFirstName] = useState('John')
    const [lastName, updateLastName] = useState('Doe')
    const [email, updateEmail] = useState('[email protected]')
    const [gender, updateGender] = useState('M')
    const [age, updateAge] = useState('20')
    const [isStaff, updateIsStaff] = useState(false)

    const [isReady, setReady] = useState(false);

    
    useEffect(() => {
        getCurrentUserInfo();
    }, []);     //called only when component mounted 

    const getCurrentUserInfo = async () => {

        try {
            const tokenValidity = await isTokenValid(navigation)
            console.log('token valid? ',tokenValidity)
            if (tokenValidity){
                const auth_key = await AsyncStorage.getItem('auth_key');

                const res = await fetch('http://chouhanaryan.pythonanywhere.com/auth/users/me/', {
                    method: 'GET',
                    headers: {
                        Authorization: `Token ${auth_key}`,
                    },
                })
    
                const data = await res.json()
                console.log(data)
                const firstName = data.first_name
                const lastName = data.last_name
                const age = data.age.toString()
                const email = data.email
                const gender = data.gender === 'F' ? 'Female' : 'Male'
                const isStaff = data.is_staff
    
                //set user details to state
                updateAge(age)
                updateEmail(email)
                updateFirstName(firstName)
                updateLastName(lastName)
                updateGender(gender)
                updateIsStaff(isStaff)
    
                if (res.status === 200) {
                    setReady(true);
                }
            } else {
                logout(navigation)
            }

        } catch (err) {
            console.log('error' , err)
        }
    }

    const onSavePressed = async () => {

        // validation
        if (firstName === "" || lastName === "" || age === "") {
            if (firstName === "")
                Alert.alert('please enter firstName')
            else if (lastName === "")
                Alert.alert('please enter lastName')
            else if (age === "")
                Alert.alert('please enter age')
        }
        else {
            try {
                let formData = new FormData()
                formData.append('email', email)
                formData.append('first_name', firstName)
                formData.append('last_name', lastName)
                formData.append('age', age)
                // console.log(formData)

                const auth_key = await AsyncStorage.getItem('auth_key');

                const res = await fetch('http://chouhanaryan.pythonanywhere.com/auth/user_update/', {
                    method: 'POST',
                    headers: {
                        Authorization: `Token ${auth_key}`,
                    },
                    body: formData,
                })
                console.log(res)
                console.log(res.status)
                const resJson = await res.json()
                console.log(resJson)
                if (res.status === 200) {
                    Alert.alert('details updated')
                } else {
                    Alert.alert('Error in updating details')
                }
                toggleEditMode(!editMode)
            } catch (err) {
                console.log(err)
            }
        }
    }

    return (
        <ScrollView style={{ flex: 1 }}>
            <Header style={{ backgroundColor: '#4796BD', flexDirection: 'row' }} androidStatusBarColor="#247096">
                <Left>
                    <TouchableOpacity onPress={() => { navigation.navigate('Drawer') }}>
                        <Icon name="home" color="white" size={35} />
                    </TouchableOpacity>
                </Left>
                <Body>
                    <Text style={{ fontSize: 21, color: '#fff' }}>Profile</Text>
                </Body>

            </Header>

            {/* container */}

            {!isReady &&
                <Body style={{ justifyContent: 'center' }}>
                    <ActivityIndicator size="large" color="#000" />
                </Body>
            }

            {
                isReady &&
                <View >
                    <View style={{ alignItems:'center',marginTop: 20, }}>
                        {/* <Text style={styles.profileTitle}>  </Text> */}

                        {!editMode && <TouchableOpacity style={styles.editButton} onPress={() => toggleEditMode(!editMode)}>
                            <Icon name="edit" color="#4796BD" size={25} />
                            <Text style={styles.editText}> Edit </Text>
                        </TouchableOpacity>}


                    </View>

                    <View style={{ alignItems: 'center' }}>
                        <View floatingLabel style={styles.inputBox}>
                            <Label style={styles.label}>First Name</Label>
                            <Input
                                style={editMode ? styles.inputAreaEditMode : styles.inputAreaViewMode}
                                // placeholder="Username"
                                value={firstName}
                                disabled={editMode ? false : true}
                                onChangeText={val => updateFirstName(val.trim())}
                            />
                        </View>

                        <View floatingLabel style={styles.inputBox}>
                            <Label style={styles.label}>Last Name</Label>
                            <Input
                                style={editMode ? styles.inputAreaEditMode : styles.inputAreaViewMode}
                                // placeholder="Username"
                                value={lastName}
                                disabled={editMode ? false : true}
                                onChangeText={val => updateLastName(val.trim())}
                            />
                        </View>

                        <View style={styles.inputBox}>
                            <Label style={styles.label}>Email</Label>
                            <Input
                                style={styles.inputAreaViewMode}
                                // placeholder="Username"
                                value={email}
                                disabled={true}
                            />
                        </View>


                        <View style={styles.inputBox}>
                            <Label style={styles.label}>Gender</Label>

                            <Input
                                style={styles.inputAreaViewMode}
                                // placeholder="Username"
                                value={gender}
                                disabled={true}
                            />
                        </View>

                        <View style={styles.inputBox}>

                            <Label style={styles.label}>Age</Label>
                            <Input
                                keyboardType="numeric"
                                style={editMode ? styles.inputAreaEditMode : styles.inputAreaViewMode}
                                onChangeText={val => updateAge(val.trim())}
                                value={age}
                                disabled={editMode ? false : true}
                            />
                        </View>


                        <View style={styles.inputBox}>

                            <Label style={styles.label}>is staff?</Label>
                            <Text style={styles.inputAreaViewMode}> {isStaff ? "true" : "false"}</Text>
                        </View>



                        {/* {
                            editMode &&
                            <View style={styles.inputBox}>

                                <Label style={styles.label}> is staff? </Label>
                                <View style={styles.radioGroup}>
                                    <Text style={styles.isStaffText}> true </Text>
                                    <Radio selected={isStaff} />

                                    <Text style={styles.isStaffText}> false </Text>
                                    <Radio selected={!isStaff} />
                                </View>
                            </View>
                        } */}

                        {/* end of userinput */}

                    </View>
                    {/* end of form */}
                    {
                        editMode &&
                        <TouchableOpacity style={styles.saveButton} onPress={() => onSavePressed()}>
                            {/* <Icon name="edit" color="#4796BD" size={25} /> */}
                            <Text style={styles.editText}> Save </Text>
                        </TouchableOpacity>
                    }


                    <TouchableOpacity
                        style={styles.logoutButton}
                        onPress={() => {
                            logout(navigation)
                        }}>
                        <Text style={styles.logoutText}>Logout</Text>
                    </TouchableOpacity>

                </View>}
        </ScrollView>
    );
}
Example #26
Source File: LeftDays.js    From ovuli with MIT License 4 votes vote down vote up
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>
  );
}