How do I store and get the theme state using AsyncStorage - react-native

I'm tying to store the theme state in the app, so that the chosen theme will be persistent after the app is closed. I have two files, one is the App.js file which has the navigation, and the other is the DrawerContent.js file that has the content of the drawer as well as the switch for the theme. toggleTheme is passed to the DrawerContent through useContext.
These are the snippets of the App file.
import {
NavigationContainer,
DefaultTheme as NavigationDefaultTheme,
DarkTheme as NavigationDarkTheme
} from '#react-navigation/native';
import {
Provider as PaperProvider,
DefaultTheme as PaperDefaultTheme,
DarkTheme as PaperDarkTheme
} from 'react-native-paper';
import AsyncStorage from '#react-native-community/async-storage';
const THEME_KEY = 'theme_color';
export default function App() {
const [isDarkTheme, setIsDarkTheme] = useState(false);
{/* Themes */ }
const CustomDefaultTheme = {
...NavigationDefaultTheme,
...PaperDefaultTheme,
colors: {
...NavigationDefaultTheme.colors,
...PaperDefaultTheme.colors,
background: '#ffffff',
text: '#333333',
tab: '#0789DC'
}
}
const CustomDarkTheme = {
...NavigationDarkTheme,
...PaperDarkTheme,
colors: {
...NavigationDarkTheme.colors,
...PaperDarkTheme.colors,
background: '#333333',
text: '#ffffff',
tab: '#2c3e50'
}
}
const theme = isDarkTheme ? CustomDarkTheme : CustomDefaultTheme;
// AsyncSotrage
const storeTheme = async (key, isDarkTheme) => {
try {
await AsyncStorage.setItem(THEME_KEY, JSON.stringify(isDarkTheme))
setIsDarkTheme(isDarkTheme);
console.log(isDarkTheme)
} catch (error) {
alert(error);
}
}
const getTheme = async () => {
try {
const savedTheme = await AsyncStorage.getItem(THEME_KEY)
if (savedTheme !== null) {
setIsDarkTheme(JSON.parse(savedTheme));
}
} catch (error) {
alert(error);
}
}
const authContext = useMemo(() => ({
toggleTheme: () => {
setIsDarkTheme(isDarkTheme => !isDarkTheme);
// storeTheme(isDarkTheme => !isDarkTheme);
console.log(isDarkTheme);
}
}),
[]
);
useEffect(() => {
getTheme();
// Fetch the token from storage then navigate to our appropriate place
const bootstrapAsync = async () => {
let userToken;
try {
userToken = await AsyncStorage.getItem(USER_TOKEN)
if (userToken !== null) {
setUserToken(JSON.parse(userToken))
}
} catch (e) {
alert(e)
}
// After restoring token, we may need to validate it in production apps
// This will switch to the App screen or Auth screen and this loading
// screen will be unmounted and thrown away.
dispatch({ type: 'RESTORE_TOKEN', token: userToken });
};
bootstrapAsync();
}, []);
return (
<PaperProvider theme={theme}>
<AuthContext.Provider value={authContext}>
<NavigationContainer theme={theme}>
...
</NavigationContainer>
</AuthContext.Provider>
</PaperProvider>
)
}
This is the DrawerContent code.
import {
useTheme,
Avatar,
Title,
Caption,
Paragraph,
Drawer,
Text,
TouchableRipple,
Switch
} from 'react-native-paper';
export function DrawerContent(props) {
const paperTheme = useTheme();
const { signOut, toggleTheme } = React.useContext(AuthContext);
return (
<View style={{ flex: 1 }}>
<DrawerContentScrollView>
<View style={styles.drawerContent}>
...
<Drawer.Section title="Preferences">
<TouchableRipple onPress={() => { toggleTheme() }}>
<View style={styles.preference}>
<Text>Dark Theme</Text>
<View pointerEvents="none">
<Switch
value={paperTheme.dark}
/>
</View>
</View>
</TouchableRipple>
</Drawer.Section>
</View>
</DrawerContentScrollView>
</View>
)
}

Perhaps the effective synchronous access of AsyncStorage can solve your problem. It is recommended that you use the react-native-easy-app open source library react-native-easy-app, through which you can access any data in AsyncStorage like memory objects.
For specific usage, maybe you can refer to the StorageController file in Project Sample_Hook

Related

React native expo camera "no access to camera" error

I have installed the expo camera tool with npm.
I run this code and it works on Snack :
import React, { useState, useEffect } from "react";
import { Text, View, StyleSheet, Button } from "react-native";
import { BarCodeScanner } from "expo-barcode-scanner";
import { Camera } from "expo-camera";
export default function Scanner() {
const [hasPermission, setHasPermission] = useState(null);
const [scanned, setScanned] = useState(false);
useEffect(() => {
(async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === "granted");
})();
}, []);
const handleBarCodeScanned = ({ type, data }) => {
setScanned(true);
alert(`Bar code with type ${type} and data ${data} has been scanned!`);
};
if (hasPermission === null) {
return <Text>Requesting for camera permission</Text>;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View style={styles.container}>
<Camera
style={StyleSheet.absoluteFillObject}
onBarCodeScanned={console.log}
barCodeScannerSettings={{
barCodeTypes: [BarCodeScanner.Constants.BarCodeType.qr],
}}
/>
{scanned && (
<Button title={"Tap to Scan Again"} onPress={() => setScanned(false)} />
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "column",
justifyContent: "center",
},
});
But in localhost I have the message "no access to camera"and I have no popup asking for access.
I am a complete beginner with react native and I can't figure out how to fix this ^^.
EDIT : I'm running it on web

Invalid hook call. Hooks can only be called inside of the body of a function component. : barcode-scanner

I try to use the barcode-scanner on my react native app, but a I get this error :
Invalid hook call. Hooks can only be called inside of the body of a function component.
That is the code source of my component :
import React, { useState, useEffect, Component } from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';
class QrCode extends Component {
render () {
const [hasPermission, setHasPermission] = useState(null);
const [scanned, setScanned] = useState(false);
useEffect(() => {
(async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
const handleBarCodeScanned = ({ type, data }) => {
setScanned(true);
alert(`Bar code with type ${type} and data ${data} has been scanned!`);
};
if (hasPermission === null) {
return <Text>Requesting for camera permission</Text>;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View style={styles.container}>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={StyleSheet.absoluteFillObject}
/>
{scanned && <Button title={'Tap to Scan Again'} onPress={() => setScanned(false)} />}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
});
export default QrCode;

Cannot update a component (`ForwardRef(BaseNavigationContainer)`) while rendering a different component (`Signinscreen`)

I am getting the following warning:
Warning: Cannot update a component (ForwardRef(BaseNavigationContainer)) while rendering a different component (Signinscreen). To locate the bad setState() call inside Signinscreen, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
Signinscreen.js
import React, { Component, useEffect } from 'react'
import { View, Text, TextInput, Image } from 'react-native'
// STYLE
import styles from "./style"
// FORMIK
import { Formik } from 'formik'
// COMPONENT
import Navigationcomponent from "../../assets/components/navigationcomponent"
// STORAGE
import AsyncStorage from '#react-native-async-storage/async-storage'
// REDUX
import { connect } from 'react-redux'
// REDUX ACTION
import { initialaccount,user_signin } from '../../actions/index'
// YUP
import * as yup from 'yup'
// IMAGE
const mainimage = require("../../assets/images/mainlogo.png")
// SCREEN
import Homescreen from "../homescreen";
const SigninSchema = yup.object().shape({
username: yup
.string()
.min(6)
.max(12)
.required('Please, provide your username!')
.nullable(),
password: yup
.string()
.min(6)
.required('Please, provide your password!')
.nullable(),
})
const Signinscreen = ({navigation, initialaccount_d, user_signin_d, user_s}) => {
const storeData = async (values) => {
try {
// await AsyncStorage.setItem('me', JSON.stringify(values))
// await initialaccount_d(true)
// console.log(values)
await user_signin_d(values)
//
// navigation.navigate("Initialhomescreen")
} catch (e) {
// saving error
}
}
const validatecheck = () => {
AsyncStorage.setItem('me', JSON.stringify(user_s.usersignin_success))
navigation.navigate("Initialhomescreen")
// console.log(user_s.usersignin_success)
// if (user_s.usersignin_success != null) {
// // console.log(user_s.usersignin_success)
// // navigation.navigate("Initialhomescreen")
// if (user_s.usersignin_success.status == 200) {
// // console.log("user_s.usersignin_success")
// await AsyncStorage.setItem('me', JSON.stringify(user_s.usersignin_success))
// navigation.navigate("Initialhomescreen")
// }
// }
}
// ONBACK PRESS
useEffect(() => {
// validatecheck()
navigation.addListener('beforeRemove', e => {
// REMOVE INPUT VALUE BEFORE LEAVE SCREEN
user_signin_d(null)
});
},[])
if (user_s.usersignin_success != null && user_s.usersignin_success.status == 200) {
// validatecheck()
return(
<View>
{validatecheck()}
<Text>Load...</Text>
</View>
)
} else {
return(
<Formik
// validationSchema={SigninSchema}
initialValues={{ username: null, password: null}}
onSubmit={values => storeData(values)}>
{({ handleChange, handleSubmit, values, errors, touched }) =>
(
<View style={styles.main}>
<View style={styles.mainconf}>
<Image style={styles.imageconf} source={mainimage}></Image>
<View style={styles.inputconfmain}>
<Text style={styles.titleconf}>
Create now, for ever...
</Text>
<TextInput
style={styles.inputconf}
placeholder="username"
placeholderTextColor="gray"
onChangeText={handleChange('username')}
value={values.username}>
</TextInput>
{touched.username && errors.username &&
<Text style={{ fontSize: 12, color: 'red', alignSelf: "center" }}>{errors.username}</Text>
}
<TextInput
style={styles.inputconf}
placeholder="password"
placeholderTextColor="gray"
secureTextEntry={true}
onChangeText={handleChange('password')}
value={values.password}>
</TextInput>
{touched.password && errors.password &&
<Text style={{ fontSize: 12, color: 'red', alignSelf: "center" }}>{errors.password}</Text>
}
<Text onPress={handleSubmit} style={styles.btnsignupconf}>
Sign in
</Text>
{user_s.usersignin_success != null ? (user_s.usersignin_success.status == 400 ? <Text style={styles.warningmsg}>{user_s.usersignin_success.message}</Text> : (null)) : null}
</View>
</View>
</View>
)}
</Formik>
)
}
}
const mapStateToProps = (state) => ({
user_s: state.user
})
const mapDispatchToProps = (dispatch) => ({
initialaccount_d: (value) => dispatch(initialaccount(value)),
user_signin_d: (value) => dispatch(user_signin(value))
})
export default connect(mapStateToProps, mapDispatchToProps)(Signinscreen)
Homescreen.js
import React, { Component, useEffect, useState } from 'react'
import { View, Text, Image, SafeAreaView, BackHandler } from 'react-native'
// COMPONENT
import Navigationcomponent from "../../assets/components/navigationcomponent";
// STORAGE
import AsyncStorage from '#react-native-async-storage/async-storage';
// STYLE
import styles from "./style"
// REDUX
import { connect } from 'react-redux'
// REDUX ACTION
import { initialaccount } from '../../actions/index'
const Homescreen = ({navigation, initialaccount_s, initialaccount_d, user_s}) => {
// useEffect(() => {
// myaccount()
// }, []);
// myaccount = async () => {
// try {
// const value = await AsyncStorage.getItem('me')
// if(value !== null) {
// // value previously stored
// console.log('Yay!! you have account.')
// // await navigation.navigate("Homescreen")
// await initialaccount_d(true)
// } else {
// console.log('Upss you have no account.')
// // await navigation.navigate("Welcomescreen")
// await initialaccount_d(false)
// }
// } catch(e) {
// // error reading value
// }
// }
// Call back function when back button is pressed
const backActionHandler = () => {
BackHandler.exitApp()
return true;
}
useEffect(() => {
console.log(user_s.usersignin_success)
// Add event listener for hardware back button press on Android
BackHandler.addEventListener("hardwareBackPress", backActionHandler);
return () =>
// clear/remove event listener
BackHandler.removeEventListener("hardwareBackPress", backActionHandler);
},[])
// const validatecheck = () => {
// console.log(user_s.usersignin_success)
// // if (user_s.usersignin_success == null || user_s.usersignin_success.status == 400) {
// // navigation.navigate("Signinscreen")
// // }
// }
clearAll = async () => {
try {
await AsyncStorage.clear()
await initialaccount_d(false)
navigation.navigate("Initialscreen")
console.log('Done. cleared')
} catch(e) {
console.log('Upss you have no account.')
}
}
const getData = async () => {
try {
const value = await AsyncStorage.getItem('me')
if(value !== null) {
// value previously stored
console.log(value)
} else {
console.log('Upss you have no account.')
}
} catch(e) {
// error reading value
}
}
return(
<View style={styles.main}>
<View style={styles.logoutconf}>
<Text onPress={() => clearAll()}>LOGOUT</Text>
<Text onPress={() => getData()}>cek data</Text>
</View>
<Navigationcomponent style={styles.mainconf} />
</View>
)
}
const mapStateToProps = (state) => ({
initialaccount_s: state.user,
user_s: state.user
})
const mapDispatchToProps = (dispatch) => ({
initialaccount_d: (value) => dispatch(initialaccount(value))
})
export default connect(mapStateToProps, mapDispatchToProps)(Homescreen)
I encountered the same problem and I think that passing navigation.navigate("<screen_name>");} to another screen's onPress() prop (like
onPress={() => {navigation.navigate("<screen_name>");}
or
...
const navFunction = () => {
navigation.navigate("<screen_name>");
};
return(
<TouchableOpactiy onPress={() => {navFunction();} />
...
</TouchableOpacity>
);
...
).
I solved this by not passing the navigation from the onPress prop in the homeScreen and instead using the navigation prop inherent to the otherScreen.
// The homescreen.
const App = props => {
return(
<TouchableOpactiy
onPress={() => {
props.navigation.navigate('OtherScreen');
}}
>...</TouchableOpacity>
);
};
// The other screen.
const App = ({navigation}) => {
return(
<TouchableOpacity
onPress={() => {
navigation.navigate('HomeScreen');
}}
>...</TouchableOpacity>
);
};

Change screen without a click event using navigation stack react native

Well what I'm trying to do is when he finishes reading the qr code is to move to the next screen as soon as this event ends. I tried to do this by declaring:
const handleBarCodeScanned = ({ type, data }) => {
{this.props.navigation.navigate ('testScreen', {data1, data2})}
}
Usually, the documentation always shows accompanied by an onClick () function associated with a button.
import React, { useState, useEffect } from 'react';
import { Text, View, StyleSheet, Button, PermissionsAndroid } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';
import wifi from 'react-native-android-wifi';
export default function QrCodeScreen() {
const [hasPermission, setHasPermission] = useState(null);
const [scanned, setScanned] = useState(false);
useEffect(() => {
(async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
const handleBarCodeScanned = ({ type, data }) => {
{this.props.navigation.navigate('nextScreen', { data1, data2 })}//Change screen
})}
};
if (hasPermission === null) {
return <Text>Requesting for camera permission</Text>;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<View
style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'flex-end',
}}>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={StyleSheet.absoluteFillObject}
/>
{scanned && <Button title={'Tap to Scan Again'} onPress={() => setScanned(false)} />}
</View>
);
}
Seems like you're using functional components so there is no this context.
You forget to import and init the navigation hook
import { useNavigation } from '#react-navigation/native';
And
export default function QrCodeScreen() {
const navigation = useNavigation();
...
Then
const handleBarCodeScanned = ({ type, data }) => {
navigation.navigate('nextScreen', { data1, data2 })
})}
I managed to solve the error by passing as the navigation parameter in the function declaration.
Before
export default function QrCodeScreen() {
}
After
export default function QrCodeScreen({navigation}) {
}
Change screen
navigation.navigate('SetupConnectionScreen');

how to show Loader till API get data using redux?

I am new to react and redux. I have implemented API fetching using redux but not sure where should i put code for loader till API gives data and error message if no network or API fails.
everything is working fine I am getting data too..only thing i stick is how to show activity indicator and error message. Is there any way to do that? Thanks in advance :)
reducer.js
export const GET_REPOS = 'my-awesome-app/repos/LOAD';
export const GET_REPOS_SUCCESS = 'my-awesome-app/repos/LOAD_SUCCESS';
export const GET_REPOS_FAIL = 'my-awesome-app/repos/LOAD_FAIL';
const initialState = {
repos: [],
loading: false,
error: null
};
export default function reducer(state = initialState , action) {
switch (action.type) {
case GET_REPOS:
return { ...state, loading: true };
case GET_REPOS_SUCCESS:
return { ...state, loading: false, repos: action.payload.data };
case GET_REPOS_FAIL:
return {
...state,
loading: false,
error: 'Error while fetching repositories',
};
default:
return state;
}
}
export function listRepos(photos) {
return {
type: GET_REPOS,
payload: {
request: {
url: `photos/`
}
}
};
}
export function listThumb(albumId) {
return {
type: GET_REPOS,
payload: {
request: {
url: `photos?albumId=${albumId}`
}
}
};
}
home.js
import React, { Component } from 'react';
import { ActivityIndicator } from 'react-native-paper';
import { View, Text, FlatList, StyleSheet, TouchableOpacity } from 'react-native';
import { connect } from 'react-redux';
import styles from '../HomeComponent/style';
import { Ionicons } from '#expo/vector-icons';
import { listRepos } from '../../../reducer';
class Home extends Component {
componentDidMount() {
this.props.dispatch(fetchProducts());
this.props.listRepos('');
}
FlatListItemSeparator = () => (
<View style={styles.flatListItemSeparator} />
)
renderItem = ({ item }) => (
<View style={styles.listRowContainer}>
<TouchableOpacity onPress={() => this.props.navigation.navigate('ThumbnailViewScreen', {
albumID: item.id,
})} style={styles.listRow}>
<View style={styles.listTextNavVIew}>
<Text style={styles.albumTitle}> {item.title} </Text>
<Ionicons name='md-arrow-dropright' style={styles.detailArrow} />
</View>
</TouchableOpacity>
</View>
);
render() {
const { error, loading, products } = this.props;
if (error) {
return <Text>adadf </Text>;
}
if (loading) {
return (
<View style={{ flex: 1, paddingTop: 30 }}>
<ActivityIndicator animating={true} size='large' />
</View>
);
}
const { repos } = this.props;
return (
<View style={styles.MainContainer} >
<FlatList
styles={styles.container}
data={repos}
renderItem={this.renderItem}
ItemSeparatorComponent={this.FlatListItemSeparator}
/>
</View>
);
}
}
const mapStateToProps = state => {
let storedRepositories = state.repos.map(repo => ({ key: repo.id, ...repo }));
return {
repos: storedRepositories
};
};
const mapDispatchToProps = {
listRepos
};
export default connect(mapStateToProps, mapDispatchToProps)(Home);
const mapStateToProps = state => {
let storedRepositories = state.repos.map(repo => ({ key: repo.id, ...repo }));
return {
repos: storedRepositories
};
};
loading may not have been passed as a prop to Home. To fix that,
add it to mapStateToProps:
return {
repos: storedRepositories,
loading: state.loading
};