how can i manage errors in code push updating? - react-native

I'm trying to manage errors with a try catch in my application.
For example in this case if there's no connection , to catch the error with my application going without codepush to interfere .
Simply stop codepush if there are errors and go on with the application's functionality.
here is my code:
import React, {useEffect, useState} from 'react';
import {NavigationContainer} from '#react-navigation/native';
import codePush from 'react-native-code-push';
import {LoaderBox, ProgressBox} from '#components';
import {Navigator} from '#navigator';
export default function App() {
const [syncMessage, setSyncMessage] = useState(true);
const [syncProgress, setSyncProgress] = useState(false);
const [progress, setProgress] = useState(0);
const codePushStatusDidChange = (status: any) => {
try {
switch (status) {
case codePush.SyncStatus.CHECKING_FOR_UPDATE:
setSyncMessage(true);
break;
case codePush.SyncStatus.DOWNLOADING_PACKAGE:
console.log('Downloading package.');
setSyncMessage(false);
setSyncProgress(true);
break;
case codePush.SyncStatus.INSTALLING_UPDATE:
console.log('Installing update.');
setSyncProgress(true);
setSyncMessage(false);
break;
case codePush.SyncStatus.UP_TO_DATE:
console.log('Up-to-date.');
setSyncMessage(false);
break;
case codePush.SyncStatus.UPDATE_INSTALLED:
console.log('Update installed.');
setSyncProgress(false);
break;
}
} catch (err) {}
};
const codePushDownloadDidProgress = (progression: {
receivedBytes: any;
totalBytes: any;
}) => {
let progressReceived = Math.round(
(progression.receivedBytes / progression.totalBytes) * 100,
);
setProgress(progressReceived);
};
useEffect(() => {
codePush.sync(
{installMode: codePush.InstallMode.IMMEDIATE},
codePushStatusDidChange,
codePushDownloadDidProgress,
);
}, []);
return (
<NavigationContainer>
{syncMessage && <LoaderBox />}
{!syncMessage && !syncProgress && <Navigator />}
{syncProgress && <ProgressBox prog={progress} />}
</NavigationContainer>
);
}
thank u in advance for the help

wrap the function like this:
const codePushStatusDidChange = (status: any) => {
try {
switch (status) {
case codePush.SyncStatus.CHECKING_FOR_UPDATE: {
setSyncMessage(true);
break;
}
case codePush.SyncStatus.DOWNLOADING_PACKAGE:
console.log('Downloading package.');
setSyncMessage(false);
setSyncProgress(true);
break;
case codePush.SyncStatus.INSTALLING_UPDATE:
console.log('Installing update.');
setSyncProgress(true);
setSyncMessage(false);
break;
case codePush.SyncStatus.UP_TO_DATE:
console.log('Up-to-date.');
setSyncMessage(false);
break;
case codePush.SyncStatus.UPDATE_INSTALLED:
console.log('Update installed.');
setSyncProgress(false);
break;
}
} catch (err) {}
setSyncMessage(false);
};

Related

react-native-vision-camera device is null

I am trying to run a basic example of react-native-vision-camera and getting the error device is null. I checked the app permissions through android phone and camera permissions are granted. Here is my current code:
import React,{useEffect, useState} from 'react';
import { Text, View, Linking} from 'react-native';
import {useCameraDevices, Camera} from 'react-native-vision-camera';
const App = () => {
const devices = useCameraDevices();
const device = devices.back;
React.useEffect( () => {
requestCameraPermission();
}, [])
const requestCameraPermission = React.useCallback( async () => {
const permission = await Camera.requestCameraPermission();
if (permission == 'denied')
{
console.log("Permission not granted");
await Linking.openSettings();
}
}, [])
function renderCamera()
{
if(device == null)
{
console.log("device is null");
return (<View><Text>Camera not working</Text></View>)
}
else
{
<View>
<Camera
device={device}
isActive={true}
enableZoomGesture
/>
</View>
}
}
return(
<View>
{renderCamera()}
</View>
)
}
export default App;

React Native AsyncStorage not working - now what am I doing wrong?

What am I leaving out here?
At this point I just want to see it write a value and retrieve a value. By setting the variable "appType" I can see if it's working. It is not because the initial value of "appType" is not changing. I can tell this by which page is loading. I need this information upfront to determine which page is to load first.
import 'react-native-gesture-handler';
import React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import AsyncStorage from '#react-native-community/async-storage';
import SpMyPage from './screens/s_mypg';
import UsMyPage from './screens/u_mypg';
import UsRegPage from './screens/u_regs';
function checkAsyncStorage(){
var appType = '';
const storeData = async () => {
try {
await AsyncStorage.setItem('random_time', '50000')
} catch (e) {
// saving error
}
}
const getData = async () => {
try {
const value = await AsyncStorage.getItem('random_time')
if(value !== null) {
// value previously stored
appType = 'S';
}
else {
appType = 'U';
}
} catch(e) {
// error reading value
appType = 'U';
}
}
return appType;
}
function PreHomeScreen() {
var appType = checkAsyncStorage();
if (appType == 'S') {
return <SpMyPage />;
}
else {
if (appType == 'U') {
return <UsMyPage />;
}
else {
return <UsRegPage />;
}
}
}
/* ************************************************************************** */
const Stack = createStackNavigator();
function App() {
return (
<>
<NavigationContainer>
<Stack.Navigator
initialRouteName = "PreHomeScreen"
screenOptions={{
headerShown: false,
}}>
<Stack.Screen name="PreHomeScreen" component={PreHomeScreen} />
<Stack.Screen name="SpMyPage" component={SpMyPage} />
<Stack.Screen name="UsMyPage" component={UsMyPage} />
<Stack.Screen name="UsRegPage" component={UsRegPage} />
</Stack.Navigator>
</NavigationContainer>
</>
);
};
export default App;
I think the right way to import AsynStorage is
import AsyncStorage from '#react-native-community/async-storage';
Here's an example from the repo.
https://github.com/react-native-community/async-storage/blob/master/example/examples/GetSetClear.js
My original goal was to use AsyncStorage.
I coded it the way the examples showed.
But, I found that apparently I don't need to have an "async function" wrapped around the AsyncStorage methods. Hence no "await" needed either. Not sure if this is going to cause a problem but for now it seems to work.
function checkAsyncStorage(){
var appType = '';
try {
AsyncStorage.setItem('random_time', '50000')
} catch (e) {
// saving error
}
try {
const value = AsyncStorage.getItem('random_time')
if(value !== null) {
// value previously stored
appType = 'S';
}
else {
appType = '';
}
} catch(e) {
// error reading value
appType = 'U';
}
return appType;
}
// The import statement should be like:
import AsyncStorage from '#react-native-community/async-storage';
// The function to retrieve previously stored data (In this example it's "userId")
retrieveData = async () => {
try {
const userId = await AsyncStorage.getItem('userId');
if (userId != null) {
console.log(userId);
}
} catch (e) {
console.log(e);
}
};
// The function to store data (In this example it's "userId")
storeData = async () => {
try {
await AsyncStorage.setItem('userId', value);
} catch (e) {
console.log(e);
}
};

How to use react-native-image-picker with Redux in React-native

I'am trying to use react-native-image-picker function inside the reducer to change the avatar but the image is not changing.
i can solve this by writing the image picker function inside the avatar.js file but i want to use this way.
if anyone knows how to solve this problem please.
here is my code :
avatarReducer.js
import ImagePicker from 'react-native-image-picker';
const initialState = {avatar: require('../../Images/ic_tag_faces.png')};
function setAvatar(state = initialState, action) {
var nextState;
switch (action.type) {
case 'SET_AVATAR':
ImagePicker.showImagePicker({}, response => {
if (response.didCancel) {
console.log("L'utilisateur a annulé");
} else if (response.error) {
console.log('Erreur : ', response.error);
} else {
console.log('Photo : ', response.uri);
var requireSource = {uri: response.uri};
nextState = {
...state,
avatar: requireSource,
};
return nextState || state;
}
});
return state;
default:
return state;
}
} // end function
export default setAvatar;
Avatar.js
import React from 'react';
import {StyleSheet, Image, TouchableOpacity} from 'react-native';
import {connect} from 'react-redux';
class Avatar extends React.Component {
constructor(props) {
super(props);
}
_setAvatar() {
const action = {type: 'SET_AVATAR'};
this.props.dispatch(action);
}
render() {
return (
<TouchableOpacity
style={styles.touchableOpacity}
onPress={() => this._setAvatar()}>
<Image style={styles.avatar} source={this.props.avatar} />
</TouchableOpacity>
);
}
} // end class
const mapStateToProps = state => {
return {
avatar: state.setAvatar.avatar,
};
};
export default connect(mapStateToProps)(Avatar);

mapStateToProps does not re-render the component after state change

I've been working with React/React-Native for a while now, but I'm new to Redux and I cannot find the problem. I have a RESTFull API and two main modules: the service model and the price model. Once the admin user adds a new service the user can also associate a price for that service. The problema is that when I add a service (in the NewServiceScreen) my code dispatches an action to change the redux store and therefore update the service list on the NewPriceScreen for the user to associate a price with the service that was just added.
NewPriceScreen.js
function mapStateToProps(state){
return {
newPrice: state.newPriceReducer
}
}
// Exports the connected NewPriceScreen
export default connect(mapStateToProps)(NewPriceScreen);
NewServiceScreen
...
handleSubmit = async() => {
const { descricao } = this.props.newService;
const userToken = await AsyncStorage.getItem('token');
axios.post('/estabelecimento/servicos/',{descricao: descricao}, {
headers: {
"Authorization": `Token ${userToken}`
}
})
.then(res => {
Alert.alert(
'Deu tudo certo :)',
'Dados salvos com sucesso !',
);
console.log(res.data);
this.props.dispatch({type: 'addService', newService: res.data});
})
.catch(error =>{
Alert.alert(
'Ops ! Algo aconteceu :(',
error.message,
);
})
}
...
const mapStateToProps = state => ({
newService: state.newService
});
export default connect(mapStateToProps)(NewServiceScreen);
Reducers.js
const initialState = {
servicos: [],
// Database variables
servico: 0,
duracao: '',
custo: '',
comissao: ''
}
export default function newPriceReducer(state = initialState, action){
// console.log("My state")
// console.log(state);
switch(action.type){
case 'setState': {
return {
...state,
servico: action.descricao,
duracao: action.duracao,
custo: action.custo,
comissao: action.comissao
}
}
case "ADD_SERVICES": {
// console.log("Servicos");
const newState = {
...state,
servicos: action.servicos
}
// console.log(newState);
// console.log(newState === initialState)
return newState;
}
case 'addService': {
// console.log("ADD Service");
servicos = state.servicos;
servicos.push(action.newService);
const newState = {
...state,
servicos: servicos
}
// console.log(newState);
// console.log(newState === initialState);
return newState
}
default:
return state;
}
}
const initialState = {
descricao: ''
}
export default function newServiceReducer(state = initialState, action){
switch(action.type){
case 'setDescricao': {
return {
...state,
descricao: action.descricao
}
}
default:
return state;
}
}
App.js
import { createStore, applyMiddleware, combineReducers } from "redux";
import thunkMiddleware from 'redux-thunk'
import newServiceReducer from '../reducers/NewService';
import newPriceReducer from "../reducers/NewPrice";
import logger from 'redux-logger';
const mainReducer = combineReducers({
newService: newServiceReducer,
newPriceReducer
})
const store = createStore(mainReducer, applyMiddleware(logger));
export default store
import React from 'react';
import { Platform, StatusBar, StyleSheet, View, AsyncStorage, ImageBackground} from 'react-native';
import { AppLoading, Asset, Font, Icon } from 'expo';
import AppNavigator from './navigation/AppNavigator';
// Redux Stuff
import {Provider} from 'react-redux';
import AppStore from './store/App';
export default class App extends React.Component {
state = {
isLoadingComplete: false,
isLoggedIn: false,
};
render() {
if (!this.state.isLoadingComplete && !this.props.skipLoadingScreen) {
return (
<AppLoading
startAsync={this._loadResourcesAsync}
onError={this._handleLoadingError}
onFinish={this._handleFinishLoading}
/>
);
} else {
return (
<Provider store={AppStore}>
<ImageBackground source={require('./assets/images/back.png')} style={{width: '100%', height: '100%'}}>
{Platform.OS === 'ios' && <StatusBar barStyle="default" />}
<AppNavigator />
</ImageBackground>
</Provider>
);
}
}
}
In lines:
servicos = state.servicos;
servicos.push(action.newService);
I was making some sort mutation. I just changed it to:
const newState = {
...state,
servicos: [...state.servicos, action.newService]
}

bundling failed: SyntaxError in D:\RN\AtmosphericMeshing-\src\router.js: D:/RN/AtmosphericMeshing-/src/router.js: Unexpected token (16:0)

everyone, I have been reporting wrong when I used the react-native compilation project, I don't know how to solve it, I can't find the error, please give me some Suggestions, thank you very much.
import React, { PureComponent } from 'react';
import { BackHandler, Platform, View, StatusBar, Text,Modal } from 'react-native';
import {
addNavigationHelpers
} from 'react-navigation';
import { connect } from 'react-redux';
import moment from 'moment';
import SplashScreen from 'react-native-splash-screen';
import { loadToken, getNetConfig, saveNetConfig, loadNetConfig } from './dvapack/storage';
import { createAction, NavigationActions, getCurrentScreen } from './utils';
import NetConfig from './config/NetConfig.json';
import api from './config/globalapi';
import AppNavigator from './containers/';
*I don't know if this is the correct way of writing the router, and it has led to this problem.*
#connect(({ router }) => ({ router }))***//一直报这里的错误=I've been making mistakes here.***
class Router extends PureComponent {
constructor(props) {
super(props);
this.state = {
configload: true
};
}
async componentWillMount() {
let netconfig =await loadNetConfig();
if (!netconfig && !netconfig != null) {
if (NetConfig.isAutoLoad) {
const newconfig = [];
NetConfig.Config.map((item, key) => {
const netitem = {};
// netitem.neturl = `http://${item.configIp}:${item.configPort}`+api.appurl;
netitem.neturl = `http://${item.configIp}:${item.configPort}`;
if (key === 0) {
netitem.isuse = true;
} else {
netitem.isuse = false;
}
newconfig.push(netitem);
});
saveNetConfig(newconfig);
} else {
this.setState({ configload: false });
SplashScreen.hide();
}
}
BackHandler.addEventListener('hardwareBackPress', this.backHandle);
}
async componentDidMount() {
const user = await loadToken();
this.props.dispatch(createAction('app/loadglobalvariable')({ user }));
}
componentWillUnmount() {
if (Platform.OS === 'android') {
BackHandler.removeEventListener('hardwareBackPress', this.backHandle);
JPushModule.removeReceiveCustomMsgListener(receiveCustomMsgEvent);
JPushModule.removeReceiveNotificationListener(receiveNotificationEvent);
JPushModule.removeReceiveOpenNotificationListener(openNotificationEvent);
JPushModule.removeGetRegistrationIdListener(getRegistrationIdEvent);
JPushModule.clearAllNotifications();
} else {
DeviceEventEmitter.removeAllListeners();
NativeAppEventEmitter.removeAllListeners();
}
}
backHandle = () => {
const currentScreen = getCurrentScreen(this.props.router);
//登录
if (currentScreen === 'Login') {
return true;
}
if (currentScreen !== 'Home') {
this.props.dispatch(NavigationActions.back());
return true;
}
return false;
}
render() {
if (!this.state.configload) {
return (
<View style={{ flex: 1 }}>
<StatusBar
barStyle="light-content"
/>
{/* <ScanNetConfig ScanSuccess={() => {
this.setState({ configload: true });
}}
/> */}
<Text>ScanNetConfig</Text>
</View>
);
}
const { dispatch, router } = this.props;
const navigation = addNavigationHelpers({ dispatch, state: router });
return (
<View style={{ flex: 1 }}>
<AppNavigator navigation={navigation} />
</View>
);
}
}
export function routerReducer(state, action = {}) {
return AppNavigator.router.getStateForAction(action, state);
}
export default Router;
Need More Detail?
this is the error.
bundling failed: SyntaxError in D:\RN\AtmosphericMeshing-\src\router.js: D:/RN/AtmosphericMeshing-/src/router.js: Unexpected token (16:0)
I find the Solution
.babelrc needs to be changed:
{
"presets": ["react-native"],
"plugins": [
"syntax-decorators",
"transform-decorators-legacy",
["import", { "libraryName": "antd-mobile" }]
]
}