Skip to content

Commit 71a69de

Browse files
committed
fix: 🐛 add exercice Network
1 parent 8664657 commit 71a69de

File tree

2 files changed

+31
-33
lines changed

2 files changed

+31
-33
lines changed

challenges/data/03.md

Lines changed: 1 addition & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -23,39 +23,7 @@ yarn add @react-native-community/netinfo
2323
npm install --save @react-native-community/netinfo
2424
```
2525

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-
};
58-
```
26+
- [ ] Create a new file `Network.tsx` and [paste this component](https://raw.githubusercontent.com/flexbox/react-native-workshop/main/hackathon/spacecraft/src/components/exercice/Network.tsx)
5927

6028
You can use console.log to check if the user is connected to the internet.
6129

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import NetInfo from "@react-native-community/netinfo";
2+
import type { PropsWithChildren } from "react";
3+
import React, { createContext, useContext, useEffect, useState } from "react";
4+
5+
interface NetworkContextProps {
6+
isConnected: boolean | null;
7+
}
8+
9+
const NetworkContext = createContext<NetworkContextProps>(
10+
{} as NetworkContextProps
11+
);
12+
13+
export const NetworkProvider = ({ children }: PropsWithChildren) => {
14+
const [isConnected, setIsConnected] = useState<boolean | null>(false);
15+
16+
useEffect(() => {
17+
// use `NetInfo.addEventListener` to listen to network status changes
18+
// use `NetInfo.fetch` to get the current network status
19+
// store the network status in the `isConnected` state
20+
return () => {
21+
// unsubscribe from the network status listener
22+
};
23+
}, [isConnected]);
24+
25+
return (
26+
{/* Add `NetworkContext.Provider` with the connection status value */ }
27+
);
28+
};
29+
30+
export const useNetwork = () => useContext(NetworkContext);

0 commit comments

Comments
 (0)