|
3 | 3 |
|
4 | 4 | import * as React from 'react' |
5 | 5 |
|
6 | | -// 🐨 create your CountContext here with React.createContext |
| 6 | +const CountContext = React.createContext() |
7 | 7 |
|
8 | | -// 🐨 create a CountProvider component here that does this: |
9 | | -// 🐨 get the count state and setCount updater with React.useState |
10 | | -// 🐨 create a `value` array with count and setCount |
11 | | -// 🐨 return your context provider with the value assigned to that array and forward all the other props |
12 | | -// 💰 more specifically, we need the children prop forwarded to the context provider |
| 8 | +function useCountContext() { |
| 9 | + const context = React.useContext(CountContext) |
| 10 | + if (!context) { |
| 11 | + throw new Error('useCount must me used within the CountProvider.') |
| 12 | + } |
| 13 | + return context |
| 14 | +} |
| 15 | + |
| 16 | +function CountProvider(props) { |
| 17 | + const [count, setCount] = React.useState(0) |
| 18 | + const value = [count, setCount] |
| 19 | + return <CountContext.Provider value={value} {...props} /> |
| 20 | +} |
13 | 21 |
|
14 | 22 | function CountDisplay() { |
15 | | - // 🐨 get the count from useContext with the CountContext |
16 | | - const count = 0 |
| 23 | + const [count] = useCountContext() |
17 | 24 | return <div>{`The current count is ${count}`}</div> |
18 | 25 | } |
19 | 26 |
|
20 | 27 | function Counter() { |
21 | | - // 🐨 get the setCount from useContext with the CountContext |
22 | | - const setCount = () => {} |
23 | | - const increment = () => setCount(c => c + 1) |
| 28 | + const [, setCount] = useCountContext() |
| 29 | + const increment = () => { |
| 30 | + setCount(c => c + 1) |
| 31 | + } |
24 | 32 | return <button onClick={increment}>Increment count</button> |
25 | 33 | } |
26 | 34 |
|
27 | 35 | function App() { |
28 | 36 | return ( |
29 | 37 | <div> |
30 | | - {/* |
31 | | - 🐨 wrap these two components in the CountProvider so they can access |
32 | | - the CountContext value |
33 | | - */} |
34 | | - <CountDisplay /> |
35 | | - <Counter /> |
| 38 | + <CountProvider> |
| 39 | + <CountDisplay /> |
| 40 | + <Counter /> |
| 41 | + </CountProvider> |
36 | 42 | </div> |
37 | 43 | ) |
38 | 44 | } |
|
0 commit comments