React Native, the Android lifecycle and navigation - javascript

We are building a React Native app that uses redux-persist to store the app state, including the navigation state. I would like for this app to behave like a native app in terms of navigation:
When a native Android app goes into the background, is eventually stopped by the OS and is then moved into the foreground, it will resume in the Activity where the user previously left off. If the same app is killed by the user (or a crash), it will open at the main Activity.
For a RN app, this means that redux-persist should persist and restore the navigation state in the componentWillMount of the app, but only if the app was not killed by the user.
The following code works:
componentWillMount() {
if (global.isRelaunch) {
// purge redux-persist navigation state
}
global.isRelaunch = true;
...
But it looks hackish and I also do not understand why the global scope survives.
What is the proper way to detect whether an RN app was re-opened from the background? (ideally with iOS support)

You should take a look to AppState which is an api that provided by react-native
check this example:
import React, {Component} from 'react'
import {AppState, Text} from 'react-native'
class AppStateExample extends Component {
state = {
appState: AppState.currentState
}
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = (nextAppState) => {
if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
console.log('App has come to the foreground!')
}
this.setState({appState: nextAppState});
}
render() {
return (
<Text>Current state is: {this.state.appState}</Text>
);
}
}

#semirturgay's answer is one way to do detect leaving the app. For Android, it is way better to detect home or recent app button clicks. This is because fragments within your app from other apps like social media or photos will also trigger background state, which you don't want because they are still in the app adding a photo to a profile from the camera etc. You can easily detect home and recent app button clicks on Android with react-native-home-pressed. This library simply exposes the android button events.
First install the library with npm i react-native-home-pressed --save and then link it react-native link. Then rebuild your app and add the following snippet.
import { DeviceEventEmitter } from 'react-native'
class ExampleComponent extends Component {
componentDidMount() {
this.onHomeButtonPressSub = DeviceEventEmitter.addListener(
'ON_HOME_BUTTON_PRESSED',
() => {
console.log('You tapped the home button!')
})
this.onRecentButtonPressSub = DeviceEventEmitter.addListener(
'ON_RECENT_APP_BUTTON_PRESSED',
() => {
console.log('You tapped the recent app button!')
})
}
componentWillUnmount(): void {
if (this.onRecentButtonPressSub) this.onRecentButtonPressSub.remove()
if (this.onHomeButtonPressSub) this.onHomeButtonPressSub.remove()
}
}

Related

Designing persistent layouts in Next.js

I'm going through this article and I'm trying to figure out how the persistence is supposed to occur in Option 4. From what I can tell, you'd need to redefine the .getLayout for every page. I'm not sure how the logic for nesting is incorporated into further urls.
Here's the code from the article
// /pages/account-settings/basic-information.js
import SiteLayout from '../../components/SiteLayout'
import AccountSettingsLayout from '../../components/AccountSettingsLayout'
const AccountSettingsBasicInformation = () => <div>{/* ... */}</div>
AccountSettingsBasicInformation.getLayout = page => (
<SiteLayout>
<AccountSettingsLayout>{page}</AccountSettingsLayout>
</SiteLayout>
)
export default AccountSettingsBasicInformation
// /pages/_app.js
import React from 'react'
import App from 'next/app'
class MyApp extends App {
render() {
const { Component, pageProps, router } = this.props
const getLayout = Component.getLayout || (page => page)
return getLayout(<Component {...pageProps}></Component>)
}
}
export default MyApp
For example, say AccountSettingsBasicInformation.getLayout is /settings/, how would I use this template to produce something at /settings/username
P.S. If someone has done something in the past they'd recommend over this, I'm open to ideas.
Yes, you have to redefine the getLayout function to every page. As long as the SiteLayout component stays “unchanged” (eg.no props change) the rendered content in that layout component (not the page content itself) stays persistent. This is because React wont rerender that component.
I used Adam’s article when I was building next.js lib for handlin modal routes. You can check the example folder where you can see I am defining the getLayout property on every page which should be rendered with layout.
Example: https://github.com/svobik7/next-bodies/tree/master/example

React-Redux: Best way to restrict user access to certain pages if they are not logged in

I am new to React/Redux, and I am working on a React application. I have been learning the basic concepts of Redux such as Store, Actions, Reducers, Middleware and the connect() function.
However, for some of the pages in my application, I want to allow only users that are logged in to be able to access them, otherwise they are redirected back to the home page of the application.
I was wondering what is the best method to be able to achieve this task? I have heard that React Router can be used to do this, but are there any better ways? Any insights are appreciated.
As you suggested the router already, using it this works neatly n safely supposing the user is only set in the redux state, when properly authenticated in the login:
import { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router-dom':
const mapStateToProps = (state) => {
return {
user: state.user
}
}
class MyPageWrapper extends Component {
componentWillMount() {
if(!this.props.user) this.props.history.push('/login');
}
render() {
return (
<div>
<YourPage/>
</div>
);
}
}
export default connect(mapStateToProps)(withRouter(MyPageWrapper));

React PWA - enforce update on click

community,
I am doing "programmatic presentations" using React (CLI) and PWA (register()). Everything works just fine, but anytime some changes are made, the URL of the final app needs to be changed so all changes are loaded.
The whole mechanism works like this:
The final app is sent to Github,
this private repo is connected to Netlify,
Netlify generates a unique URL,
users visit this Netlify URL and hit "add to home screen" on iPad,
the whole app runs under the Safari engine.
If any change in the code is made, I have to change the link in Netlify and send this new link to a people.
The process mentioned above works just fine, but honestly, it would be nice to have some kind of functionality that allows request latest update on demand - let's say - on click of a button.
Is something like that possible?
Thank you for comments!
Kind Regards
Linc
At serviceWorker.js file can find this code
if (config && config.onUpdate) {
config.onUpdate(registration);
}
So implement the config.onUpdate funtion
Create a file swConfig.js
export default {
onUpdate: registration => {
registration.unregister().then(() => {
window.location.reload()
})
},
}
At index.js send the implement function to serviceWorker
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import swConfig from './swConfig'
ReactDOM.render(<App />,
document.getElementById('root'));
serviceWorker.register(swConfig);
Check out this repo
https://github.com/wgod58/create_react_app_pwaupdate
If you want to control the update with a button click, I did using the following snippet:
Note: If your app must work offline, you should add some extra logic to verify if the user has internet connection, as the following code would break the app if it's unable to fetch the service-worker.
import React from 'react';
function App(){
const updateApp = () => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then((registration) => {
registration.unregister().then(() => {
window.location.reload();
});
});
}}
return(
<div style={{margin:"auto"}}>
<button onClick={updateApp}>
Update App
</button>
</div>
);
}
https://gist.github.com/juliomilani/6492312d1eb657d06b13c9b87d5ad023

Onsen UI implement login with React

While migrating our Onsen v1 app (based on AngularJS1) to Onsen v2 with React, I bumped into a little problem: implementing logic regarding user authentication (redirecting to login screen if there are no "saved credentials")
Here's how my app is structured...
Entry point is the App.js file, which looks like this:
import React from 'react';
import {Navigator} from 'react-onsenui';
import Home from './Home';
import Login from './Login';
class App extends React.Component {
renderPage(route, navigator) {
route.props = route.props || {};
route.props.key = route.comp.displayName;
route.props.navigator = navigator;
return React.createElement(route.comp, route.props);
}
render() {
return (
<Navigator
initialRoute={{comp: Home}}
renderPage={this.renderPage}
/>
);
}
}
export default App;
You can see that I have my references for both 'Home' and 'Login' components, however, I want to decide which component to render.
I tried the following: use 'Home' as the initialRoute, and decide in the Home components constructor if we need to go to the Login page.
constructor(props) {
super(props);
this.state = {
isOpen: false
};
const authenticated = GetAuthenticated();
if(!authenticated) {
this.props.navigator.pushPage({comp: Login});
}
}
This simply did not work, the Login page was never shown.
So basically, what I would like to do is to look in the localStorage for user credentials (or any other place for storing these kind of information), and based on this decide whether to load up the 'Home' page or the 'Login' page.
If GetAuthenticated() is a fetch call you need to remember it acts asynchronously. I'd recommend a loading section whilst the fetch is pending and then a decision on the result of the method.
This link is a good example of how you can use componentDidMount to demonstrate pending async calls. Once that is implemented you can go on to do your switch.
DO NOT, and I can't stress this enough, store user credentials in localStorage ever. Never ever.

How to make a default page in React Native?

Why I have index.android.js as default. How I can make a home.js as default?
When your platform-specific code is more complex, you should consider splitting the code out into separate files. React Native will detect when a file has a .ios. or .android. extension and load the relevant platform file when required from other components.
see: https://facebook.github.io/react-native/docs/platform-specific-code.html#platform-specific-extensions
so if you add .android.js or .ios.js to your extension RN will pick one of them based on the platform. If you want the same component for both platform just don't add platform specific extension and use just foo.js
I think what you asked for can be done this way:
import { AppRegistry } from 'react-native';
import Home from './path/to/home';
AppRegistry.registerComponent('SBlank', () => Home);
By doing this in both your index.android.js and index.ios.js you redirect your app to Home.js file.
Bonus: In addition to knowbody's answer, you can use Platform object to change how your code works on different platforms. For example:
render() {
if (Platform.OS === 'android') {
return this.renderAndroid();
}
return this.renderIOS();
}
where you import Platform by adding
import { Platform } from 'react-native';

Categories

Resources