Using NetInfo middleware in React Native with Redux

Viewed 2736

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?

3 Answers

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