|
9 | 9 |
|
10 | 10 | ## 👾 Before we start the exercise
|
11 | 11 |
|
12 |
| -- [ ] We are going to install and use `react-native-offline` |
13 |
| -- [ ] Have a look at [`react-native-offline` documentation](https://github.com/rgommezz/react-native-offline) |
| 12 | +- [ ] We are going to install and use `@react-native-community/netinfo` |
| 13 | +- [ ] Have a look at [`@react-native-community/netinfo` documentation](https://github.com/react-native-netinfo/react-native-netinfo) |
14 | 14 |
|
15 | 15 | ## 👨🚀 Exercise 3
|
16 | 16 |
|
17 |
| - |
18 |
| - |
19 | 17 | - [ ] Install the library
|
20 | 18 |
|
21 | 19 | ```console
|
22 |
| -npm install react-native-offline |
| 20 | +yarn add @react-native-community/netinfo |
| 21 | +``` |
| 22 | +```console |
| 23 | +npm install --save @react-native-community/netinfo |
| 24 | +``` |
| 25 | + |
| 26 | +- [ ] Create a new context `Network.tsx` |
| 27 | + |
| 28 | +You should check if the user is connected to the internet and display a message when the user is not connected. |
| 29 | + |
| 30 | +```javascript |
| 31 | +const NetworkContext = createContext<NetworkContextProps>( |
| 32 | + {} as NetworkContextProps |
| 33 | +); |
| 34 | + |
| 35 | +export const NetworkProvider = ({ children }: PropsWithChildren) => { |
| 36 | + const [isConnected, setIsConnected] = useState<boolean | null>(false); |
| 37 | + |
| 38 | + useEffect(() => { |
| 39 | + const unsubscribe = NetInfo.addEventListener((state) => { |
| 40 | + setIsConnected(state.isConnected); |
| 41 | + }); |
| 42 | + |
| 43 | + NetInfo.fetch().then((state) => { |
| 44 | + setIsConnected(state.isConnected); |
| 45 | + }); |
| 46 | + |
| 47 | + return () => { |
| 48 | + unsubscribe(); |
| 49 | + }; |
| 50 | + }, [isConnected]); |
| 51 | + |
| 52 | + return ( |
| 53 | + <NetworkContext.Provider value={{ isConnected }}> |
| 54 | + {children} |
| 55 | + </NetworkContext.Provider> |
| 56 | + ); |
| 57 | +}; |
23 | 58 | ```
|
24 | 59 |
|
| 60 | +You can use console.log to check if the user is connected to the internet. |
| 61 | + |
25 | 62 | - [ ] Update the entry point of your application to add a new provider
|
26 | 63 |
|
27 | 64 | ```javascript
|
28 |
| -import { NetworkProvider } from 'react-native-offline'; |
| 65 | +import { NetworkProvider } from '~/contexts/Network'; |
29 | 66 | ```
|
30 | 67 |
|
31 | 68 | `NetworkProvider` will injects the network state to children components via [React Context](https://reactjs.org/docs/context.html).
|
|
0 commit comments