Using NetInfo middleware in React Native with Redux - javascript

I want to test in all components whether the user has connection to the internet.
I could use NetInfo in each component, but since I am using redux, I thought it could be done easier with a middleware(?).
I have used
import { createStore, applyMiddleware } from 'redux';
const netInfo = store => next => action => {
const listener = (isConnected) => {
store.dispatch({
type: types.NET_INFO_CHANGED,
isConnected,
});
};
NetInfo.isConnected.addEventListener('change', listener);
NetInfo.isConnected.fetch().then(listener);
return next(action);
};
const store = createStore(AppReducer, applyMiddleware(netInfo));
where AppReducer is just combineReducers(navReducer, netInfoReducer, ...).
It does seem to work, but I am really worried if this performs well enough. It seems it is only run once, but I am never removing the listener or anything.
Is this how you normally would do if you want to populate all components with an isConnected variable?

I would create a Higher-Order Component for this:
import React, { Component } from 'react';
import { NetInfo } from 'react-native';
function withNetInfo(WrappedComponent) {
return class extends Component {
constructor(props) {
super(props);
this.state = {};
this.handleChange = this.handleChange.bind(this);
NetInfo.isConnected.fetch().then(this.handleChange);
}
componentDidMount() {
NetInfo.isConnected.addEventListener('change', this.handleChange);
}
componentWillUnmount() {
NetInfo.isConnected. removeEventListener('change', this.handleChange);
}
handleChange(isConnected) {
this.setState({ isConnected });
}
render() {
return <WrappedComponent isConnected={this.state.isConnected} {...this.props} />;
}
}
}
export default withNetInfo;
Then you can wrap whatever component you would like to render:
class MyComponent extends Component {
render() {
const { isConnected } = this.props;
return(
<View>
<Text>
{`Am I connected? ${isConnected}`}
</Text>
</View>
);
}
}
export default withNetInfo(MyComponent);
Bonus: if you want to keep the statics methods of your original component (if you have defined some) you should use the package hoist-non-react-statics to copy the non-react specific statics:
import React, { Component } from 'react';
import { NetInfo } from 'react-native';
import hoistStatics from 'hoist-non-react-statics';
function withNetInfo(WrappedComponent) {
class ExtendedComponent extends Component {
constructor(props) {
super(props);
this.state = {};
this.handleChange = this.handleChange.bind(this);
NetInfo.isConnected.fetch().then(this.handleChange)
}
componentDidMount() {
NetInfo.isConnected.addEventListener('change', this.handleChange);
}
componentWillUnmount() {
NetInfo.isConnected. removeEventListener('change', this.handleChange);
}
handleChange(isConnected) {
this.setState({ isConnected });
}
render() {
return <WrappedComponent isConnected={this.state.isConnected} {...this.props} />;
}
}
return hoistStatics(ExtendedComponent, WrappedComponent);
}
export default withNetInfo;

There shouldn't be a performance issue using middleware to keep "isConnected" in your redux store, but you would want to make sure the listener is only added once. I use https://github.com/michaelcontento/redux-middleware-oneshot to achieve that.

I considered middleware, too, but was also afraid how to handle the sub/unsub. I've decided to go with adding and removing the listener in componentDidMount and componentWillUnmount of my AppContainer class, which holds the rest of the app in my MainNavigator. This class' lifecycle should follow that of the app, and thus make sure to sub/unsub correctly. I am, however, also going to use a redux action to set the status and listen to it in the relevant views to show a 'no connection' banner.

Related

Unable to update redux store - React Native

I am new to using redux for React Native and am testing it with a simple case. I have been able to successfully connect to the store, and I can see the action is dispatched properly using the redux debugger, however, the store is not updating in the debugger. I've tried several different implementations, but nothing is working. Any help would be appreciated!
Component:
import React, { PureComponent } from 'react'
import { Text, TouchableOpacity, SafeAreaView, Alert, Button } from 'react-native'
import { Navigation } from 'react-native-navigation';
import { connect } from 'react-redux'
import simpleAction from '../store/actions/simpleAction'
class App2 extends PureComponent {
constructor(props){
super(props);
}
pressRedux = () => {
const data = 'hello'
this.props.simpleAction(data)
}
render() {
return (
<SafeAreaView>
<Text>
{this.props.state.simpleReducer.text}
</Text>
<Button onPress = {this.pressRedux} title = 'Redux' />
</SafeAreaView>
)
}
}
function mapStateToProps(state) {
return {
state: state
};
}
const mapDispatchToProps = {
simpleAction
}
export default connect(mapStateToProps, mapDispatchToProps)(App2);
Action:
import {SET_TEXT} from '../types/types'
export default function simpleAction(data) {
return({
type: SET_TEXT,
payload: data
})
}
reducer:
import SET_TEXT from '../types/types'
const INITIAL_STATE = {
text: 'Hi'
}
const simpleReducer = (state = INITIAL_STATE, action ) => {
switch(action.type){
case SET_TEXT:
return { ...state, text: action.payload};
default:
return state;
}
}
export default simpleReducer;
The code you've shared here looks correct. Only thing I can suggest is, if you're seeing the action come through in the debugger, your issue is either with the data/payload or logic within simpleReducer.
In this case you have it properly stripped down so I'd almost think this isn't actually the code you are running, it might be something in your build process?

How To Run React Native lifecycle on another Component

I tried to make a network availability component for my app.
My lifecycle component in the network.js
import { Component } from 'react';
import { NetInfo } from 'react-native';
export default class Network extends Component {
constructor(props) {
super(props);
this.state = { connected: null }
}
componentWillMount() {
NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectionChange);
NetInfo.isConnected.fetch().done((isConnected) => this.setState({ connected: isConnected }))
}
componentWillUnmount() {
NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectionChange);
}
handleConnectionChange = (isConnected) => { this.setState({ connected: isConnected }) }
situation() {
if(this.state.connected)
return true
else
return false
}
}
And my main page :
import React, { Component } from 'react';
import { View, I18nManager, StatusBar, StyleSheet, Text } from 'react-native';
import { Spinner } from 'native-base';
import Network from './Network'
export default class Intro extends Component {
constructor() {
super();
I18nManager.allowRTL(true);
I18nManager.forceRTL(true);
}
render() {
var network = new Network;
alert(network.situation())
if (network==true) {
alert('online')
else
alert('offline')
}
}
But after execution, componentWillMount and componentWillUnmount are not working.
There is really no need to make React component for checking Network connection utility. You can just create a simple Network class like this and initialize/deinitialize it from your app component's lifecycles.
import { NetInfo } from 'react-native';
const NET_INFO = {};
let instance;
export default class Network {
static getInstance() {
return instance || new Network();
}
static initialize() {
NetInfo.isConnected.addEventListener('connectionChange', Network.getInstance().handleConnectionChange);
}
static deinitialize() {
NetInfo.isConnected.removeEventListener('connectionChange', Network.getInstance().handleConnectionChange);
}
handleConnectionChange = (isConnected) => {
NET_INFO.isConnected = isConnected;
}
static isInternetConnected() {
return NET_INFO.isConnected;
}
}
App component:
import React, { Component } from 'react';
import Network from './Network'
export default class Intro extends Component {
componentWillMount() {
Network.initialize();
}
componentWillUnmount() {
Network.deinitialize();
}
render() {
const connected = Network.isInternetConnected()
if (connected ==true)
alert('online')
else
alert('offline')
}
}
Because you are not using Network class as component but as a normal class.
If you want to run life-cycle methods then you need use it as Component.
like this in render method,
<Network />
and if you want to execute anything in parent for network change then use prop functions.
like this in render method,
<Network
connectivityChange={()=>{
//do your stuffs here
}}
/>
you need to call this.props.connectivityChange() in Network component when you want do something in parent.

Trigger setState function in parent from promise.then in child

I am trying to find a solution to setState from a parent within child promise.
The parent component is
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
transition: false
};
}
handleTransition = () => {
this.setState(state => ({ transition: !state.transition }));
};
render() {
return <Child handleTransition={this.handleTransition} />;
}
}
of which this.props.handleTransition is to be triggered from a child component as
class Child extends Component {
constructor(props) {
super(props);
this.state = {};
}
onSubmit = event => {
firebase
.doCreateUserWithEmailAndPassword(email, password)
.then(() => {
// Trigger this.props.handleTransition here
})
...
Where this.props.handleTransition is wanting to be triggered with then of onSubmit
Please let me know if you require more detail? I would prefer not to use a library or package to achieve this but if it makes life easier I may consider. Redux is likely the best option but I would prefer not to unless necessary.
Note: this.props.handleTransition(); does the job but esLint returns an error of Must use destructuring props assignmenteslint(react/destructuring-assignment) and I am considering that this method is not the correct method.
// --- parent.js
import React, { Component, Fragment } from "react";
import { ChildComponent } from './containers/child'
class ParentContainer extends Component {
handleUpdate = () => {
// whatever you want to do here
}
render(){
return (
<Fragment>
<ChildComponent onUpdate={this.handleUpdate} />
</Fragment>
);
}
}
export default ParentContainer;
// --- child.js
import React, { Component, Fragment } from "react";
export class ChildComponent extends Component {
this.someAsyncFunction = () => {
fetch('/just/for/example')
.then(res =>
// Do whatever you need here, then hit your function on parent by bubbling the request up the chain
this.props.onUpdate();
)
}
render(){
return (
// whatever you want to do with this data
);
}
}

React how to apply`componentDidMount()

I am using redux and reactjs. I need to add few function in componentDidMount() to the following root react component.
I am not using react class extend. How can I apply componentDidMount() and my logic there?
const App = () => (
<div>
<NavigationContainer />
</div>
)
export default App
You can wrap the JSX in a return call and simply do your logic before, even interacting with your redux store.
const App = () => {
const willRunOnEachRender = 'runs on each render'
return (<div>
<NavigationContainer willRunOnEachRender={willRunOnEachRender} />
</div>
)
}
export default App
import Dispatcher from "./Dispatcher.jsx";
class TodoStore extends EventEmitter
{
getInitialState: function() {
return { };
},
componentWillMount: function() {
},
changeevent()
{
.. your logic
this.emit("change");
}
componentDidMount: function() {
..your logic
},
handleActions(action)
{
if(action='your action')
{
changevent()
}
}
)
window.Dispatcher=Dispatcher;
Dispatcher.register(todoStore.handleActions.bind(todoStore));
after the change event is fired in changevent you can catch that event wherever you want
In this case you need to use stateful components or wrap it inside a stateful container, stateless components don't support the lifecycle in React.
So I recommend you import component from react and do something like below code:
import React, {Component} from 'react';
class App extends React.Component {
componentDidMount() {
//your code here
}
render() {
return <div><NavigationContainer /></div>;
}
}
export default App

Dispatch different actions in redux

I have a (React) container component. It's children need different data from different api endpoints, so I want to dispatch 2 actions the same time (both are asynchronous).
This doesn't seem to be possible. If I have both dispatches, the activeSensors are always empty...
class Dashboard extends React.Component {
static propTypes = {
userData: React.PropTypes.array.isRequired,
activeSensors: React.PropTypes.object.isRequired
};
static contextTypes = {
store: React.PropTypes.object
};
constructor(props) {
super(props);
}
componentWillMount() {
const { store } = this.context;
store.dispatch(fetchActiveSensorDataForAllSensors());
store.dispatch(fetchUserData());
}
render() {
return (
<div>
<AnalyticsPanel activeSensors={this.props.activeSensors}/>
<SearchCustomer userData={this.props.userData}/>
</div>
);
}
}
export default connect((state)=> {
return {
userData: state.userData.data,
activeSensors: state.activeSensorsAll.sensors
}
})(Dashboard);
EDIT: See the source for the full component.
I haven't used the this.context.store.dispatch method your code uses, but I don't think that its necessarily the way you should be doing things. Primarily because it really muddies the line between container and presentational components. Presentational components don't need access to store, and there are other methods to do this which don't have this (albeit pedantic) drawback.
My component files typically look like this:
import React from 'react';
import { connect } from 'react-redux';
import * as actions from './actions';
export class Container from React.Component {
componentWillMount() {
// Most conical way
const { fetchActiveSensorDataForAllSensors, fetchUserData } = this.props;
fetchActiveSensorDataForAllSensors();
fetchUserData();
// Less conical way
// const { dispatch } = this.props;
// const { fetchActiveSensorDataForAllSensors, fetchUserData } = actions;
// dispatch(fetchActiveSensorDataForAllSensors());
// dispatch(fetchUserData());
}
render() {
return (
<div>
<AnalyticsPanel activeSensors={this.props.activeSensors}/>
<SearchCustomer userData={this.props.userData}/>
</div>
);
}
}
function mapStateToProps(state) {
return {
activeSensors: state.activeSensorsAll.sensors,
userData: state.userData.data
}
}
export default connect(mapStateToProps, actions)(Container);

Categories

Resources