Skip to content

Commit

Permalink
feat: add imperative api to refresh state (#594)
Browse files Browse the repository at this point in the history
* feat: add imperative api to refresh state
* docs: document refresh in README
* Add example to example app
* Update netinfo mock with refresh method
  • Loading branch information
roryabraham committed Apr 22, 2022
1 parent 7f040ce commit 1d7b751
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 1 deletion.
15 changes: 15 additions & 0 deletions README.md
Expand Up @@ -148,6 +148,7 @@ NetInfo.fetch().then(state => {
* [`NetInfoCellularGeneration`](#netinfocellulargeneration)
* **Methods:**
* [`fetch()`](#fetch)
* [`refresh()`](#refresh)
* [`addEventListener()`](#addeventlistener)
* [`useNetInfo()`](#usenetinfo)

Expand Down Expand Up @@ -345,6 +346,20 @@ NetInfo.fetch("wifi").then(state => {
});
```
#### `refresh()`
Updates NetInfo's internal state, then returns a `Promise` that resolves to a [`NetInfoState`](#netinfostate) object. This is similar to `fetch()`, but really only useful on platforms that do not supply internet reachability natively. For example, you can use it to immediately re-run an internet reachability test if a network request fails unexpectedly.
**Example:**
```javascript
NetInfo.refresh().then(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
});
```
This will also update subscribers using `addEventListener` and/or `useNetInfo`.
## Troubleshooting
### Errors when building on Android
Expand Down
46 changes: 46 additions & 0 deletions example/ConnectionInfoRefresh.tsx
@@ -0,0 +1,46 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/

import * as React from 'react';
import {Text, View, TouchableOpacity} from 'react-native';
import NetInfo from '../src';

interface State {
connectionInfo: string;
}

export default class ConnectionInfoCurrent extends React.Component<
Record<string, unknown>,
State
> {
state = {
connectionInfo: 'Tap to refresh state',
};

componentDidMount(): void {
this._refreshState();
}

_refreshState = async (): Promise<void> => {
const state = await NetInfo.refresh();
this.setState({
connectionInfo: JSON.stringify(state),
});
};

render() {
return (
<View>
<TouchableOpacity onPress={this._refreshState}>
<Text style={{color: 'black'}}>{this.state.connectionInfo}</Text>
</TouchableOpacity>
</View>
);
}
}
9 changes: 9 additions & 0 deletions example/index.tsx
Expand Up @@ -23,6 +23,7 @@ import {
import ConnectionInfoSubscription from './ConnectionInfoSubscription';
import ConnectionInfoCurrent from './ConnectionInfoCurrent';
import ConnectionInfoFetch from './ConnectionInfoFetch';
import ConnectionInfoRefresh from './ConnectionInfoRefresh';
import NetInfoHook from './NetInfoHook';
import IsConnected from './IsConnected';

Expand Down Expand Up @@ -51,6 +52,14 @@ const EXAMPLES: Example[] = [
return <ConnectionInfoFetch />;
},
},
{
id: 'refresh',
title: 'NetInfo.refresh',
description: 'Refresh the state on tap',
render() {
return <ConnectionInfoRefresh />;
},
},
{
id: 'currentInfoSingle',
title: 'Current Info Single',
Expand Down
2 changes: 2 additions & 0 deletions jest/netinfo-mock.js
Expand Up @@ -16,11 +16,13 @@ const defaultState = {
const RNCNetInfoMock = {
configure: jest.fn(),
fetch: jest.fn(),
refresh: jest.fn(),
addEventListener: jest.fn(),
useNetInfo: jest.fn(),
};

RNCNetInfoMock.fetch.mockResolvedValue(defaultState);
RNCNetInfoMock.refresh.mockResolvedValue(defaultState);
RNCNetInfoMock.useNetInfo.mockReturnValue(defaultState);
RNCNetInfoMock.addEventListener.mockReturnValue(jest.fn());

Expand Down
13 changes: 13 additions & 0 deletions src/index.ts
Expand Up @@ -64,6 +64,18 @@ export function fetch(
return _state.latest(requestedInterface);
}

/**
* Force-refreshes the internal state of the NetInfo library.
*
* @returns A Promise which contains the updated connection state.
*/
export function refresh(): Promise<Types.NetInfoState> {
if (!_state) {
_state = createState();
}
return _state._fetchCurrentState();
}

/**
* Subscribe to connection information. The callback is called with a parameter of type
* [`NetInfoState`](README.md#netinfostate) whenever the connection state changes. Your listener
Expand Down Expand Up @@ -119,6 +131,7 @@ export * from './internal/types';
export default {
configure,
fetch,
refresh,
addEventListener,
useNetInfo,
};
2 changes: 1 addition & 1 deletion src/internal/state.ts
Expand Up @@ -65,7 +65,7 @@ export default class State {
this._subscriptions.forEach((handler): void => handler(nextState));
};

private _fetchCurrentState = async (
public _fetchCurrentState = async (
requestedInterface?: string,
): Promise<Types.NetInfoState> => {
const state = await NativeInterface.getCurrentState(requestedInterface);
Expand Down

0 comments on commit 1d7b751

Please sign in to comment.